NHibernate.Linq和MultiCriteria

时间:2009-03-26 06:12:57

标签: linq nhibernate linq-to-nhibernate

有人知道如何使用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语法会很不错。

感谢。

3 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:3)

NHibernate.Linq本身使用NHibernateQueryTranslator将LINQ表达式转换为ICriteria。您也可以这样做,然后将生成的ICriteria传递给您的IMultiCriteria。

答案 2 :(得分:0)

我有一个解决方案,可以使用NHibernate Linq批处理提取策略,但代码是复杂的王者。在这里列出太多了。我很快就会在devlicio.us的博客上谈论它。我在撰写第一篇文章时会更新此评论。