NHIbernate OR Criteria Query

前端 未结 3 1302
日久生厌
日久生厌 2020-12-31 13:47

I have the following mapped classes

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

Now I cannot figure out a way s

相关标签:
3条回答
  • 2020-12-31 14:07

    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>();
    
    0 讨论(0)
  • 2020-12-31 14:26

    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.

    0 讨论(0)
  • 2020-12-31 14:30

    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))
    
    0 讨论(0)
提交回复
热议问题