tags:

views:

32

answers:

2

how do i get the equivalent of sql "or" in nhibernate

I have the following method. Basically i wish to see if the keyword is found in product.Name or Product.Description.

   public ICollection<ProductCategory> FindByCompanyIdAndSearchAndPop(int companyId, string keyword)
    {
        var products = _session
            .CreateCriteria(typeof(ProductCategory))
            .CreateAlias("Product", "product", JoinType.InnerJoin)
            .Add(Restrictions.Eq("CompanyId", companyId))
            .Add(Restrictions.Eq("product.IsPopItem", true))
            .Add(Restrictions.Like("product.Name", keyword, MatchMode.Anywhere))
            .Add(Restrictions.Like("product.Description", keyword, MatchMode.Anywhere))
            .List<ProductCategory>();
        return products;
    }
+1  A: 

I believe you can use Expression.Or(restriction1,restriction2) like this:

.Add(Expression.Or(Restrictions.Like("product.Name", keyword, 
   MatchMode.Anywhere),Restrictions.Like("product.Description", keyword, 
   MatchMode.Anywhere)))

If I remember correctly you can also nest the Expression.Or's

Marcus Oldin
+5  A: 

The || operator is overloaded for Restriction, so you can write:

.Add(
    Restrictions.Like("product.Name", keyword, MatchMode.Anywhere) ||
    Restrictions.Like("product.Description", keyword, MatchMode.Anywhere)))
asgerhallas