4

I tried to upgrade NH 3.3.1.4000 to the latest version NH 4.0.2.4000 and I had an issue with FetchMany and ThenFetchMany.

In this post I learned that this old functionality is no longer valid, Breaking changes with NHibernate 4 upgrade.

What is the correct way to do this kind of fetching on the new NH version?

Code Example:

var IdsList = new List { /* Some Ids */ };
session.Query<A>()
.FetchMany(x=>x.B_ObjectsList)
.ThanFetchMany(x=>x.C_ObjectsList)
.Where(x=>IdsList.Contains(x=>x.Id))
.ToList();

Classes:

Public Class A
{
    public int Id {get;set;}
    public IList<B> B_ObjectsList{get;set;}
}

Public Class B
{
    public int Id {get;set;}
    public IList<C> C_ObjectsList {get;set;}
}

Public Class C
{
    public int Id {get;set;}
}

Mapping:

<class name="A" table="A">
<id name="Id" type="int" column="Id" unsaved-value="0">
  <generator class="identity" />
</id>
<bag name="B" table="B" inverse="false" lazy="true"
cascade="all-delete-orphan">
</class>

<class name="B" table="B">
<id name="Id" type="int" column="Id" unsaved-value="0">
  <generator class="identity" />
</id>
<bag name="C" table="C" inverse="false" lazy="true"
cascade="all-delete-orphan">
</class>


<class name="C" table="C">
<id name="Id" type="int" column="Id" unsaved-value="0">
  <generator class="identity" />
</id>
</class>
4

2 回答 2

2

大概

var IdsList = new List { /* Some Ids */ };
var results = session.Query<A>()
    .FetchMany(x => x.B_ObjectsList)
    .Where(x=>IdsList.Contains(x.Id))
    .ToList();

// initialize C_ObjectsList
var bIds = results.SelectMany(x => x.B_ObjectsList).Select(b => b.Id).Distinct().ToList();
session.Query<B>()
    .FetchMany(x => x.C_ObjectsList)
    .Where(b => bIds.Contains(b.Id))
    .ToList();

return results;
于 2015-01-14T15:52:24.257 回答
0

如果 B 引用了 A,您可以执行以下操作:

var IdsList = new List { /* Some Ids */ };
var results = session.Query<A>()
                     .Fetch(a => a.B_ObjectsList)
                     .Where(a => IdsList.Contains(a.Id))
                     .ToList();

// initialize C_ObjectsList
var aQuery = session.Query<A>()
                    .Where(x => IdsList.Contains(x.Id));

session.Query<B>()
       .Fetch(b => b.C_ObjectsList)
       .Where(b => aQuery.Contains(b.A)
       .Prefetch();

这样做的好处是不受数据库的最大参数限制,在 SQL 服务器中默认为 2100。ToList()我使用以下扩展方法代替 :

static public void Prefetch<T>(this IQueryable<T> query)
{
    // ReSharper disable once ReturnValueOfPureMethodIsNotUsed
    query.AsEnumerable().FirstOrDefault();
}
于 2017-02-02T12:13:11.613 回答