NHIbernate OR Criteria Query

☆樱花仙子☆ 提交于 2019-11-30 08:57:35

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.

The Mirage

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))

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