NHIbernate OR Criteria Query

谁都会走 提交于 2019-12-18 13:12:36

问题


I have the following mapped classes

Trade { ID, AccountFrom, AccountTo }
Account {ID, Company}
Company {ID}

Now I cannot figure out a way select all trades where

AccountFrom.Company.ID = X OR AccountTo.Company.ID = X

I can get AND to work using the following:

criteria.CreateCriteria("AccountFrom").CreateCriteria("Company").Add(Restrictions.Eq("ID", X);
criteria.CreateCriteria("AccountTo").CreateCriteria("Company").Add(Restrictions.Eq("ID", X);

But how can I transform this into an OR rather an an AND. I have used Disjunction previously, but I cannot seem to know how to add separate criteria, just restrictions.


回答1:


Try:

return session.CreateCriteria<Trade>()
    .CreateAlias("AccountFrom", "af")
    .CreateAlias("AccountTo", "at")
    .Add(Restrictions.Or(
        Restrictions.Eq("af.Company.CompanyId", companyId), 
        Restrictions.Eq("at.Company.CompanyId", companyId)))
    .List<Trade>();

I don't think you will need to alias Company.




回答2:


I think your NHibernate options depend on which version of NHibernate that you are using.

Disjunction = OR, Conjunction = AND

.Add(
  Expression.Disjunction()
    .Add(companyId1)
    .Add(companyId2)
)

Same as this question here


Jamie Ide just answered more thoroughly...the gist of it goes like this:

.Add(Restrictions.Or(
    Restrictions.Eq("object1.property1", criteriaValue), 
    Restrictions.Eq("object2.property3", criteriaValue))



回答3:


Using Linq to NHibernate:

var X = 0; // or whatever the identifier type.
var result = Session.Linq<Trade>()
                 .Where(trade => trade.AccountFrom.Company.ID == X ||
                                 trade.AccountTo.Company.ID == X)
                 .ToList();

Using HQL:

var X = 0; // or whatever the identifier type.
var hql = "from Trade trade where trade.AccountFrom.Company.ID = :companyId or trade.AccountTo.Company.ID = :companyID";
var result = Session.CreateQuery(hql)
                 .SetParameter("companyId", X)
                 .List<Trade>();


来源:https://stackoverflow.com/questions/3299022/nhibernate-or-criteria-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!