Unfortunately, I think that any approach that you could take should include a struggle with the context, and not just with the essence. As you saw, you cannot filter the navigation property directly, since it is ICollection<T> , not IQueryable<T> , so it loads immediately before you can apply any filters.
One thing you could do is create an uninsulated property in your Farm object to store a list of filtered fruits:
public class Farm { .... public virtual ICollection<Fruit> Fruits { get; set; } [NotMapped] public IList<Fruit> FilteredFruits { get; set; } }
And then in your context / repository add a method to load the Farm object and fill FilteredFruits necessary data:
public class MyDbContext : DbContext { .... public Farm LoadFarmById(int id) { Farm farm = this.Farms.Where(f => f.Id == id).Single();
This should populate myFarm.FilteredFruits just a filtered collection so that you can use it the way you want in your entity. However, I have never tried this approach myself, so there may be pitfalls that I donโt think about. One of the main drawbacks is that it will only work with Farm , which you load using this method, and not with any general LINQ queries that you execute in the MyDbContext.Farms .
All that said, I think that the fact that you are trying to do this may be a sign that you are putting too much business logic in your entity class when it really can be better in another layer. In most cases, it is better to process objects mainly as capacities for the contents of the database record and leave all filtering / processing in the repository or wherever your business logic lives. I'm not sure which application you are running, so I cannot offer any specific advice, but there is something to think about.
A very common approach if you decide to move things from a Farm object to use projection:
var results = (from farm in myContext.Farms where .... select new { Farm = farm, FilteredFruits = myContext.Fruits.Where(f => f.FarmId == farm.Id && ...).ToList() }).ToList();
... and then use the created anonymous objects for everything you want to do, instead of trying to add additional data to the Farm objects themselves.
Jeremy todd
source share