Entity Framework Code First Soft Delete Lazy Loading

匆匆过客 提交于 2019-12-02 12:57:42

问题


So I'm using Entity Framework Code First (so no .edmx) I have a base entity class with a bool IsEnabled to do soft delete's

I am using repository pattern so all queries against the repository can be filtered out with IsEnabled.

However any time I use the repository to get an MyType which is IsEnabled, Lazy Loading MyType.Items may mean that Items could be not enabled.

Is there a way, perhaps with EF Fluent to describe how to do filtering on tables?

Update:

If I have a Dbset

public class UnitOfWork : DbContext
    {
private IDbSet<MyObj> _MyObj;
public IDbSet<MyObj> MyObjs
        {
            get { return _MyObj ?? (_MyObj = base.Set<MyObj>()); }
        }
}

Is there any way I can tell the DbContext to filter the DbSet?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/9591285/entity-framework-code-first-soft-delete-lazy-loading

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