如何联接两个表查询并在Nhibernet linq中选择匹配的记录?

问题描述

我正在尝试开发一个查询,该查询使用linq-Nhibernet查询在一个结果中为两个表提供记录。

我有两个表,第一个表:account(accountId,accountDescription),第二个表:accountdescriptionhistory(accountId,description)。 AccountId是对第二个表的外键引用。现在,我正在使用下面的查询从第一个表中获取所有记录。

enter image description here

我想要的是,如果AccountDescriptionHistory中存在针对accountId引用的记录,则它应该从AccountDescriptionHistory中而不是从帐户表中返回我的描述。我想在单个查询中实现这一目标。

注意:我需要在linq NHibernate查询中使用它。

添加课程详细信息

帐户类如下:

public class Account : EntityModelHasOwner<Account>,ISupportsIdLookup
{

    /// <summary>
    /// The account number
    /// </summary>
    public virtual string AccountNumber { get; set; }

    /// <summary>
    /// The account's description
    /// </summary>
    public virtual string Description { get; set; }

}

帐户说明类别:

public class AccountDescriptionHistory : EntityModel<AccountDescriptionHistory>
{
    #region Public Properties

    /// <summary>
    /// The account description of an account that is valid for a specific date range
    /// </summary>
    public virtual string AccountDescription { get; set; }

    /// <summary>
    /// The account this AccountDescriptionHistory is associated with.
    /// </summary>
    public virtual Account Account { get; set; }
}

解决方法

您可以通过查询完成此操作。

        /* this.Session is a NHibernate.ISession */

        string hql = "FROM Account acc" +
             " inner join fetch acc.MyAccountDetails"
               "where acc.IsDeleted= :myIsDeletedParameter";
        IQuery q = this.Session.CreateQuery(hql);
        q.SetBoolean("myIsDeletedParameter",false);
        IList<Account> returnItems = q.List<Account>();
        return returnItems;

具有流利风格的或;

            ////using NHibernate;
            ////using NHibernate.Linq;

            IQueryable<Account> returnItemsQuery = (from myalias in this.Session.Query<Account>()
                .FetchMany(x => x.MyAccountDetails )
                .Where(acc => false == acc.IsDeleted)
                    select myalias);

            IList<Account> returnItems = returnItemsQuery.ToList();

我假设您的poco像这样。

public class Account
{
  /* scalars */

  public virtual ICollection<AccountDetails> MyAccountDetails {get; set;}
}

请参阅:

https://nhibernate.info/doc/howto/various/lazy-loading-eager-loading

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...