mr goose
mr goose

Reputation: 56

Loading related entities in Entity Framework: how to filter which entities should be loaded?

I have an Entity Framework model with one-to-many relationships: Client entity could have many Orders.

I want to load Client entity and all Orders made by the client except ones that are marked as Obsolete in my database.

Unfortunately, I can't use Orders.Load() because it loads all orders and doesn't accept any predicate, so I can't just write client.Orders.Load(o => !o.Obsolete).

So, how could I load only up-to-date orders?

Upvotes: 1

Views: 317

Answers (1)

Min Min
Min Min

Reputation: 6218

Use with Projection:

var client = context.Client.Select(c => new 
    { 
        Client = c, 
        Orders = c.Orders.Where(o => !o.Obsolete)
    });

Upvotes: 2

Related Questions