0

I have categories, and categories have a collection of products (Category.Products). I need to retrieve a category from the db by its id, but instead of including all its products, I want it to only include products with a given condition (example, order=0)

How can I do this with linq? I tried with:

var e = db.Categories
  .Include(a => a.products)
  .Where(a => a.products.Any(r => r.order == 0))
  .FirstOrDefault(p => p.id == id_category);
patsy2k
  • 471
  • 2
  • 8
  • Possible duplicate of [How to filter "Include" entities in entity framework?](https://stackoverflow.com/questions/39636952/how-to-filter-include-entities-in-entity-framework) – Eldho Oct 08 '18 at 07:10

3 Answers3

0

I don't think you can do that. In any case, the call to .Include() should be after any where clause, or it won't work.

Tsahi Asher
  • 1,767
  • 15
  • 28
0

In order to filter child collection you can try to select that to YouCustomModelor anonymous projection.

Note that it is not currently possible to filter which related entities are loaded. Include will always bring in all related entities Msdn reference.

var e = db.Categories
          .Where(c => c.id == id_category)
          .Select(p=> new 
          { 

             category = p,
             products = p.Products.Where(k=>k.order==0)
          }.FirstOrDefault();
Eldho
  • 7,795
  • 5
  • 40
  • 77
-1

var e = db.Categories.Where(a => a.order == 0);

Ns Turjo
  • 1
  • 8
  • This will only retrieve some categories, but won't include any products in the result. Not to mention it doesn't fit the described schema. – Tsahi Asher Oct 08 '18 at 07:02