Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHIbernate OR Criteria Query

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.

like image 650
Michal Ciechan Avatar asked Jul 21 '10 12:07

Michal Ciechan


1 Answers

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.

like image 97
Jamie Ide Avatar answered Oct 13 '22 21:10

Jamie Ide