I’m using entity framework with POCOs and the repository pattern and am wondering if there is any way to filter a child list lazy load. Example:
class Person
{
public virtual Organisation organisation {set; get;}
}
class Organisation
{
public virtual ICollection<Product> products {set; get;}
}
class Product
{
public bool active {set; get;}
}
Currently I only have a person repository because I’m always starting from that point, so ideally I would like to do the following:
Person person = personRepo.GetById(Id);
var products = person.organisation.products;
And have it only load products where active = true from the database.
Is this possible and if so how?
EDIT My best guess would be either a filter can be added to the configuration of the entity. Or there might be a way to intercept/override the lazy load call and modify it. Obviously if I created an Organisation Repository I could manually load it as I please but I am trying to avoid that.
You can do what Mark Oreta and luksan suggest while keeping all the query logic within the repository.
All you have to do is pass a
Lazy<ICollection<Product>>into the organization constructor, and use the logic they provided. It will not evaluate until you access the value property of the lazy instance.UPDATE
Now, in your repository method, when you construct the Person object you will assign the Organisation property with an
Organisationobject containing the lazy loading field.So, without seeing your whole model, it will looks something like
By using this approach, the query for the products will not be loaded until you access the
Productsproperty on theOrganisationinstance, and you can keep all your logic in the repository. There’s a good chance that I made incorrect assumptions about your model (as the sample code is quite incomplete), but I think there is enough here for you to see how to use the pattern. Let me know if any of this is unclear.