问题描述
我正在尝试开发一个查询,该查询使用linq-Nhibernet查询在一个结果中为两个表提供记录。
我有两个表,第一个表:account(accountId,accountDescription),第二个表:accountdescriptionhistory(accountId,description)。 AccountId是对第二个表的外键引用。现在,我正在使用下面的查询从第一个表中获取所有记录。
我想要的是,如果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