Nhibernate 急切地获取多个集合属性(使用QueryOver/Linq)?
我发现了两个类似的问题:Nhibernate 急切地获取多个集合属性(使用QueryOver/Linq)?,nhibernate,linq-to-nhibernate,queryover,Nhibernate,Linq To Nhibernate,Queryover,我发现了两个类似的问题: 根据: 小心不要急于去拿 同时具有多个集合属性 同时。虽然这句话 这样做很好: var employees = session.Query<Employee>() .Fetch(e => e.Subordinates) .Fetch(e => e.Orders).ToList(); var employees=session.Query() .Fetch(e=>e.下属) .Fetch(e=>e.Orders).ToLi
var employees = session.Query<Employee>()
.Fetch(e => e.Subordinates)
.Fetch(e => e.Orders).ToList();
var employees=session.Query()
.Fetch(e=>e.下属)
.Fetch(e=>e.Orders).ToList();
它执行笛卡尔乘积查询
针对数据库,所以
返回的行数将是
总下属数乘以总下属数
命令
假设我有以下模型:
public class Person
{
public virtual int Id { get; private set; }
public virtual ICollection<Book> Books { get; set; }
public virtual ICollection<Article> Articles { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
}
公共类人物
{
公共虚拟整数Id{get;private set;}
公共虚拟ICollection图书{get;set;}
公共虚拟ICollection位于下方,位于中。以下代码运行良好,只需往返数据库一次
var persons = session.QueryOver<Person>()
.Future<Person>();
var persons2 = session.QueryOver<Person>()
.Fetch(x => x.Books).Eager
.Future<Person>();
var persons3 = session.QueryOver<Person>()
.Fetch(x => x.Articles).Eager
.Future<Person>();
var persons4 = session.QueryOver<Person>()
.Fetch(x => x.Addresses).Eager
.Future<Person>();
var persons=session.QueryOver()
.Future();
var persons2=session.QueryOver()
.Fetch(x=>x.Books)。渴望
.Future();
var persons3=session.QueryOver()
.Fetch(x=>x.Articles)。急切
.Future();
var persons4=session.QueryOver()
.Fetch(x=>x.Addresses)
.Future();
公共IList GetAll()
{
var persons=session.QueryOver()
.Future();
session.QueryOver()
.Fetch(x=>x.Books)。渴望
.Future();
session.QueryOver()
.Fetch(x=>x.Articles)。急切
.Future();
session.QueryOver()
.Fetch(x=>x.Addresses)
.Future();
返回人员。ToList();
}
如果可能的话,我更喜欢使用linq提供程序,特别是如果您使用的是较新版本的nhibernate(>=4.0)。只要您的集合映射为ISET(需要.net framework>=4)我们将其转换为这样的方法,以便我们能够进行快速加载,避免笛卡尔产品。我觉得这不是一个被大量宣传的东西,但我更喜欢这种方法,在适用的情况下,胜过任何其他方法:
public class Person
{
public virtual int Id { get; private set; }
public virtual ISet<Book> Books { get; set; }
public virtual ISet<Article> Articles { get; set; }
public virtual ISet<Address> Addresses { get; set; }
}
public Person()
{
this.Books = new HashSet<Book>();
this.Articles = new HashSet<Article>();
this.Addresses = new HashSet<Address>();
}
公共类人物
{
公共虚拟整数Id{get;private set;}
公共虚拟ISet图书{get;set;}
公共虚拟ISet项目{get;set;}
公共虚拟ISet地址{get;set;}
}
公众人士()
{
this.Books=new HashSet();
this.Articles=new HashSet();
this.Addresses=newhashset();
}
如果集合的定义如上所述,则可以执行以下操作,同时避免笛卡尔积问题:
var persons = session.Query<Person>()
.FetchMany(x => x.Books)
.FetchMany(x => x.Articles)
.FetchMany(x => x.Addresses)
.ToList();
var persons=session.Query()
.FetchMany(x=>x.Books)
.FetchMany(x=>x.Articles)
.FetchMany(x=>x.Addresses)
.ToList();
请添加说明,解释您所做的工作
var persons = session.Query<Person>()
.FetchMany(x => x.Books)
.FetchMany(x => x.Articles)
.FetchMany(x => x.Addresses)
.ToList();