Entity Framework Code First Soft Delete Lazy Loading

旧街凉风 提交于 2019-12-02 07:06:16

No, there is no way to define a filter for lazy loading (also not for eager loading using Include). If you want that your navigation collections only get populated with items where IsEnabled is true you can only shape your queries accordingly, for example with explicit loading:

context.Entry(parent).Collection(p => p.Items).Query()
    .Where(i => i.IsEnabled)
    .Load();

This will populate the Items collection of parent only with the enabled items.

Edit

I feel a bit like the messenger of the bad news about a lost battle who gets his head knocked off. Maybe it's too hard to believe that Entity Framework sometimes does not have the capabilities you want. To improve my chance to convince you I add a quote from an authority, Julie Lerman:

Neither eager loading nor deferred/lazy loading in the Entity Framework allows you to filter or sort the related data being returned.

It looks like it is still possible. If you are intrested you can take a look at the Wiktor Zychla blogpost, where he gives a solution to the soft delete problem.

This http://blogs.claritycon.com/blog/2012/01/25/a-smarter-infrastructure-automatically-filtering-an-ef-4-1-dbset/ basically defines how I can achieve what I was looking for.

Basically you create a FilteredDbSet and make all your DbContext IDbSet's return it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!