gpt4 book ai didi

linq - NHibernate.Linq 和 MultiCriteria

转载 作者:行者123 更新时间:2023-12-04 01:08:50 27 4
gpt4 key购买 nike

任何人都知道使用 NHibernate.Linq 批处理 NHibernate 查询的方法,就像使用 MultiCriteria 和 ICriteria 对象一样?

使用 MultiCriteria,我可以创建如下内容:

var crit = session.CreateMultiCriteria()
.Add(session.CreateCriteria(typeof(Entity1)).Add(Restrictions.Eq("Property1","Value"))
.Add(session.CreateCriteria(typeof(Entity2)).Add(Restrictions.Eq("Property2","Value2"));

var result = crit.List();
var list1 = (IList)result[0];
var list2 = (IList)result[1];

如果我用 Linq 调用替换 CreateCriteria 调用并得到如下内容,那就太好了:
var crit = session.CreateMultiCriteria()
.Add(session.Linq<Entity1>().Where(x => x.Property1 == "Value1")
.Add(session.Linq<Entity2>().Where(x => x.Property2 == "Value2");

var result = crit.List();
var list1 = (IList<Entity1>)result[0];
var list2 = (IList<Entity2>)result[1];

我们将 Linq API 用于大多数其他查询,并且在需要运行 MultiCriteria 查询时使用相同的 Linq 语法会很好。

谢谢。

最佳答案

var query = from q in session.Linq<Person>()
where q.FirstName.StartsWith(firstName)
&& q.LastName.StartsWith(lastName)
&& q.Phones.Any(p => p.Number.Contains(phone))
select q;

// This block of code was found in the NHibernate.Linq source
// using NHibernate.Linq.Visitors;
// using NHibernate.Engine;
System.Linq.Expressions.Expression expression = query.Expression;
expression = Evaluator.PartialEval(expression);
expression = new BinaryBooleanReducer().Visit(expression);
expression = new AssociationVisitor((ISessionFactoryImplementor)session.SessionFactory).Visit(expression);
expression = new InheritanceVisitor().Visit(expression);
expression = CollectionAliasVisitor.AssignCollectionAccessAliases(expression);
expression = new PropertyToMethodVisitor().Visit(expression);
expression = new BinaryExpressionOrderer().Visit(expression);
NHibernateQueryTranslator translator = new NHibernateQueryTranslator(session);
object results = translator.Translate(expression, ((INHibernateQueryable)query).QueryOptions);

// My LINQ query converted to ICriteria
ICriteria resultsCriteria = results as ICriteria;
// Convert to criteria that returns the row count
ICriteria rowCountCriteria = CriteriaTransformer.TransformToRowCount(resultsCriteria);

IList multiResults = session.CreateMultiCriteria()
.Add(resultsCriteria.SetMaxResults(20))
.Add(rowCountCriteria)
.List();

IList people = (IList)multiResults[0];
int resultsCount = (int)((IList)multiResults[1])[0];

来自 http://rndnext.blogspot.com/2009/05/using-nhibernate-multicriteria-and-linq.html

关于linq - NHibernate.Linq 和 MultiCriteria,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/684696/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com