Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 732
Felipe Oriani Avatar asked Dec 27 '22 21:12

Felipe Oriani


2 Answers

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.

like image 85
FishBasketGordo Avatar answered Jan 10 '23 19:01

FishBasketGordo


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);
like image 34
GSerjo Avatar answered Jan 10 '23 20:01

GSerjo