NHibernate选择N + 1和递归

时间:2012-03-23 09:27:38

标签: c# nhibernate fetch recursive-query select-n-plus-1

我有几个数据类:

public class RecordGroup
{
    public virtual DataRecord RootDataRecord;
}

public class DataRecord 
{
    public virtual string Name { get; set; }
    public virtual RecordGroup RecordGroup { get; set; }
    public virtual IList<DataRecord> Children { get; set; }
    public virtual DataRecord Parent { get; set; }
    public virtual IList<DataProperty> DataProperties { get; set; }
    public virtual IList<Foto> Fotos { get; set; }
}

public class DataProperty
{
    public virtual string Name { get; set; }
    public virtual string Value { get; set; }
    public virtual IList<Foto> Fotos { get; set; }
}

public class Foto
{
    public virtual string Name { get; set; }
    public virtual byte[] Data { get; set; }
}

所以1 RecordGroup与几个DataRecords“连接”,有几个孩子(再次生孩子等),每个孩子都有几个属性和照片。 根据某个RecordGroup,我需要所有的DataRecords,包括Children,Properties和Fotos。

在原始SQL中执行此操作是一个带有少量连接的简单语句,但是当我尝试使用linq和nhibernate执行此操作时,会导致1500选择N + 1语句,并且会出现大幅减速。

我已经尝试.FetchMany( x => x.Children );

如何在1个查询中获得1个Recordgroup的整个“datatree”?

提前致谢!!!!

1 个答案:

答案 0 :(得分:1)

我想,你需要这样的东西:

   var recordGroupId = // your recordGroup Id
   Session.QueryOver<DataRecord>()
     .Where(dataRecord.RecordGroup.Id == recordGroupId)
     .Fetch(dataRecord  => dataRecord.Children).Eager
     .Fetch(dataRecord  => dataRecord.DataProperties).Eager
     .Fetch(dataRecord  => dataRecord.Fotos).Eager
     .TransformUsing(Transformers.DistinctRootEntity)
     .List<DataRecord>();