Felipe Oriani
Felipe Oriani

Reputation: 38608

Where with IN operator using Linq on NHibernate

I have a linq query with NHibernate using Session.Query<T> method and I in this query I Fetch some complex properties and collection properties. I would like to know, how can I add an condition with IN operator from an int[]? Look my code:

public IEnumerable<Product> GetProducts(int[] idCategories) 
{
    // how to add IN condition here or a subquery 
    var query = Session.Query<Product>()
                   .Where(?????)
                   .Fetch(x=>x.Category)
                   .FetchMany(x=>x.Status).ThenFetch(x=>x.Item);

    return query.ToList();
}

I have another method doing a query to get this int[] and I would like to apply it here, or if is there any way to add this subquery on the IN operator, I really appreciate!

OBS: I could convert int[] to List<int> if its necessary.

Edits

I got this int[] by a query like:

return session.Query<Category>.Where(...).Select(x => x.Id).ToArray();

My second question is, how could I add this query as a subquery to filter by category?

Thank you!

Upvotes: 4

Views: 2293

Answers (3)

GSerjo
GSerjo

Reputation: 4778

About sub query, you need Subqueries class

var query = Session.Query<Product>()
               .Where(Subqueries.WhereProperty<Product>(x=>x.Id)...)
               .Fetch(x=>x.Category)
               .FetchMany(x=>x.Status).ThenFetch(x=>x.Item);

for more details please look here How to do subqueries in nhibernate?

Upvotes: 1

GSerjo
GSerjo

Reputation: 4778

Take a look on Restrictions, for example

var query = Session.Query<Product>()
     .Where(Restrictions.In(Projections.Property<Product>x=>x.Id),idCategories))
     .Fetch(x=>x.Category)
     .FetchMany(x=>x.Status).ThenFetch(x=>x.Item);

Upvotes: 2

FishBasketGordo
FishBasketGordo

Reputation: 23142

You don't really need the IN operator. You can just do it like this:

.Where(x => idCategories.Contains(x.Category))

Note: Contains is an extension method. You need to ensure that you have a using statement for System.Linq, but you probably already have it.

Upvotes: 7

Related Questions