NHibernate 3 或 4 是否等效于实体框架的"Include"方法,该方法采用字符串参数而不是 llambda? 我想在NHibernate中做这样的事情:
Contact contact =
context.Contacts.Include("SalesOrderHeaders.SalesOrderDetails")
.FirstOrDefault();
我从这篇文章中遇到了这段代码,它在循环中使用"Fetch"很酷,但这只处理作为主对象的一级子级的对象,而上面的 EF 代码下降 2 级,不需要强类型的 llambdas。
public IQueryable<T> All<T>(params Expression<Func<T, Object>> [] fetchPaths)
{
var queryable = this.session.Query<T>();
foreach (var fetchPath in fetchPaths)
{
queryable = queryable.Fetch(fetchPath);
}
return queryable;
}
NHibernate有第二个方法称为ThenFetch。你将不得不写
this.session.Query<T>()
.Fetch(x => x.Property)
.ThenFetch(x => x.SubProperty);
似乎有几个选项可以解决我的问题。
选项 1:以以下形式动态构建 HQL:
from Contacts t0
left join fetch t0.SalesOrderHeaders t1
left join fetch t1.SalesOrderDetails t2
选项 2:使用 NHibernate 的 ICriteria.SetFetchMode。 这可以处理基于字符串的连接,这非常有用,并且比 HQL 方法更容易实现我的目的。 这是我最终编写的代码(改编自这篇文章)。 我希望这对其他人有帮助。 "GetPathsToUse"方法是我尝试使用实体框架样式的包含路径。 因此,如果我想提供"SalesOrderHeaders.SalesOrderDetails"作为唯一的路径,该方法会在"SalesOrderHeaders.SalesOrderDetails"之前先添加"SalesOrderHeaders",以便NH会很高兴。
// This also uses ICriteria, but adds some logic to auto-handle paths to reduce the number of paths needed to pass in to match how
// EntityFramework works e.g. if one path is passed in for OrderInputs.Input, this method will call SetFetchMode twice, once for OrderInputs and again for OrderInputs.Input
public T GetByIdSetFetchModeEFStyle(Guid id, ISession session, params string[] includePaths)
{
ICriteria criteria = session.CreateCriteria<T>();
if (includePaths != null && includePaths.Length > 0)
{
// NHibernate requires paths to be supplied in order. So if a path "OrderInputs.Input" is supplied, we must make
// 2 separate calls to SetFetchMode, the first with "OrderInputs", and the second with "OrderInputs.Input".
// EntityFramework handles this for us, but NHibernate requires things to be different.
List<string> pathsToUse = this.GetPathsToUse(includePaths);
foreach (string path in pathsToUse)
{
criteria.SetFetchMode(path, FetchMode.Eager);
}
}
return criteria
// prevent duplicates in the results
.SetResultTransformer(Transformers.DistinctRootEntity)
.Add(Restrictions.Eq(typeof(T).Name + "Id", id)).UniqueResult<T>();
}
private List<string> GetPathsToUse(string[] includePaths)
{
var nhPaths = new List<string>();
foreach (string path in includePaths)
{
if (!path.Contains(".") && !nhPaths.Contains(path))
{
// There is no dot in the path - just add it if it hasn't been added already
nhPaths.Add(path);
}
else
{
// We have a dot e.g. OrderInputs.Input. We need to add "OrderInputs" before "OrderInputs.Input"
string[] pathParts = path.Split(".".ToCharArray());
// Add any missing ancestors of the current path prior to adding the path
for (int p = 1; p <= pathParts.Length; p++)
{
string requiredPath = string.Join(".", pathParts.Take(p).ToArray());
if (!nhPaths.Contains(requiredPath))
{
nhPaths.Add(requiredPath);
}
}
}
}
return nhPaths;
}