且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何过滤嵌套集合实体框架对象?

更新时间:2023-02-13 13:32:44

您不能直接在整洁方式,但您有几个选项。

首先,您可以在获取商店后,明确加载子集。请参阅在显式加载相关实体时应用过滤器部分。



如果您不想额外访问数据库,您将有构建您自己的查询,并将父集合和过滤的子集合手动投影到另一个对象上。有关示例,请参阅以下问题:

Linq To Entities - 如何过滤子实体



编辑

strong>

顺便说一句,你的第一个 .Where(rcu => rcu.Orders.Select(cu => cu.Customer。删除== false))尝试不起作用,因为您将父级集合(商店)应用过滤器,而不是嵌套集合(例如,所有没有删除客户的商店) )。

逻辑上,过滤嵌套集合的代码应放在 Include 方法中。目前, Include 仅支持选择语句,但是我个人认为现在是EF团队实施类似于

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


Here is the problem : I need to return a collection of objects with filtered nested collections. E.g: there is a store with orders and I need to return a collection with stores that includes nested collections with orders but without orders from customers that are marked as deleted.

Here is what I try to do. But still no luck. Any suggestions are appriciated :)

public List<StoreEntity> GetStores(Func<Store, bool> storeFilter, Predicate<OrderEntity> orderFileter)
{
    IQueryable<StoreEntity> storeEntities = Context.Stores
        .Include(o => o.Order)
        .Include(cu => cu.Orders.Select(c => c.Customer))
        .Where(storeFilter)
        //.Where(rcu=>rcu.Orders.Select(cu=>cu.Customer.Deleted==false)) //just test this doesn't work
        .AsQueryable();

    List<StoreEntity> storeEntities = storeEntities.ToList();

    //storeEntities.ForEach(s => s.Orders.ToList().RemoveAll(c=>c.Customer.Deleted==true)); // doesn't work

    foreach (StoreEntity storeEntity in storeEntities)
    {
        storeEntity.Orders.ToList().RemoveAll(r=>r.Customer.Deleted==true);
    }

    return storeEntities;
}

The problem is that filter is not applied. Customers that have deleted flag set as true stay in the collection.

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)));