使用带有LINQ的NHibernate过滤加载导航属性

时间:2012-10-26 06:14:36

标签: nhibernate linq-to-entities

我在EF

中使用它
 var users = Context.CreateSet<User>()
             .Select(u => new {
                               User = u,
                               Salary = u.Salaries.Where(s => !s.Deleted)
                              })
                              .AsEnumerable()
                              .Select(a => a.User);

在NHibernate中有一种Linq方法可以做到这一点,我希望它也可以通过延迟加载来加载导航属性

1 个答案:

答案 0 :(得分:0)

NHibernate不会以这种方式用过滤结果填充集合,这不是一个好主意,因为你得到了一个破碎的模型。我看到的最佳选择

var users = session.Query<User>()
    .Fetch(u => u.Salaries)
    .Select(u => new
    {
        User = u,
        ActiveSalaries = u.Salaries.Where(s => !s.Deleted)
    });

public virtual IEnumerable<Salary> ActiveSalaries
{
    get { return Salaries.Where(s => !s.Deleted); }
}

var users = session.Query<User>()
    .Fetch(u => u.Salaries)

// ctor
ActiveSalaries = Salaries.Where(s => !s.Deleted);

// property
public virtual IEnumerable<Salary> ActiveSalaries { get; private set; }


// mapping almost same as that of Salaries
HasMany(x => x.ActiveSalaries).Table("Salaries").Where("Deleted=0");

var users = session.Query<User>()
    .Fetch(u => u.ActiveSalaries);