How to filter nested collection Entity Framework objects?

我只是一个虾纸丫 提交于 2019-11-26 10:36:22
Yakimych

You can't do that directly in a "neat" way, but you have a few options.
First of all, you can explicitly load the child collection after you've fetched the stores. See the Applying filters when explicitly loading related entities section.

If you don't want to make extra trips to the database, you will have to construct your own query and project the parent collection and the filtered child collections onto another object manually. See the following questions for examples:
Linq To Entities - how to filter on child entities
LINQ Query - how sort and filter on eager fetch

Edit

By the way, your first .Where(rcu=>rcu.Orders.Select(cu=>cu.Customer.Deleted==false)) attempt doesn't work since this way you are applying a filter to your parent collection (stores) rather than the nested collection (e.g. all the stores that don't have deleted customers).
Logically, the code filtering the nested collection should be placed in the Include method. Currently, Include only supports a Select statement, but personally I think it's time for the EF team to implement something like:

.Include(cu => cu.Orders.Select(c => c.Customers.Where(cust => !cust.IsDeleted)));

The problem with the code you currently have is this line:

storeEntity.Orders.ToList().RemoveAll(r=>r.Customer.Deleted==true);

storeEntity.Orders.ToList() returns a new List<OrderEntity> with the contents of storeEntity.Orders. From this new list, you remove all deleted customers. However, this list isn't used anywhere after that.

However, even if it would do what you want to, this would also remove those customers from the database, because your StoreEntity objects are still connected to the data context!

You really want to use a filter as you first tried in the commented Where. Please see Yakimych's answer for help on that.

Old topic, but I ran into a rather similar problem. I've searched a lot, and the MSDN link provided by Yakimych finally hinted me to a solution : explicitely disable lazy loading, and then do queries to filter the navigation properties. The result will then be "attached" to the main query, which would give something like that :

Context.Configuration.LazyLoadingEnabled = false;

var filteredOrders = Context.Orders.Where(x => x.Customer.Delete == false);

IQueryable<StoreEntity> storeEntities = Context.Stores
.Include(o => o.Order)
.Include(cu => cu.Orders.Select(c => c.Customer))
.Where(storeFilter)
.AsQueryable();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!