Tomislav
Tomislav

Reputation: 153

Entity framework 6 filter child object

I'm trying to get data from database with use of EF6. I have two classes

public class Manufacturer
{
  public int Id {get;set;}
  public string Name {get;set;}
  public bool Enabled {get;set;}
  public virtual IList<Product> Products {get;set;}
}

public class Product
{
  public int Id {get;set;}
  public string Name {get;set;}
  public bool Enabled {get;set;}
  public virtual Manufacturer Manufacturer {get;set;}
}

I need to get only Enabled Manufacturer with Enabled Products I tried the folowing:

var results = _context.Manufacturer
              .Where(m => m.Enabled)
              .Where(m => m.Products.Any(p => p.Enabled))
              .Select(m => new
              {
                  Manufacturer = m;
                  Product = m.Products.Where(p => p.Enabled)
              });

Unfortunaly child object are not filltered. "Products" list is alyways filled with products that are not "Enabled" Any idea?

Upvotes: 2

Views: 739

Answers (2)

Giorgi Nakeuri
Giorgi Nakeuri

Reputation: 35790

You can do it like this. But i have cheked your code and it works as well. I dont know why you getting not enabled products...

var manufacturers = (from o in _context.Manufacturer
                      where o.Enabled
                      select
                      new
                      {
                          manufacturers  = o,
                          products = o.Products.Where(c=>c.Enabled).ToList()
                      }).ToList();

Upvotes: 0

user853710
user853710

Reputation: 1767

you could go the other way around. also try including the related object.

var r = context.Products.Include("Manufacturer")
               .Where(p=>p.Enabled && p.Manufacturer.Enabled);

Upvotes: 1

Related Questions