开发者

Nested/child collections filtering in Entity Framework (ver. 1 or 4)

开发者 https://www.devze.com 2023-01-01 15:32 出处:网络
How to filter nested/child collections of entities when including them in EF? Example: Let\'s have standard Cus开发者_开发知识库tomer-Orders association. How to load all customers and include only th

How to filter nested/child collections of entities when including them in EF?

Example: Let's have standard Cus开发者_开发知识库tomer-Orders association. How to load all customers and include only their last three orders in their Orders collection?

Is there something like AssociateWith function from L2S for EF?


No, unfortunately the Object Services API in Entity Framework doesn't expose a way to selectively load associated entities based on a condition.

One way to solve this problem is to filter the associated entities when projecting the results in a query:

context.Customers.Select(c => new
    {
        Customer = c,
        LastOrders = c.Orders
                         .OrderByDescending(o => o.CreatedDate)
                         .Take(3)
                         .ToArray()
    }

Related resources:

  • Loading Related Objects (Entity Framework)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号