简体   繁体   English

实体框架6自动过滤以实现延迟加载导航属性

[英]Entity Framework 6 automatic filtering for lazy loading navigation properties

I'm implementing soft deletion in my app with IsDeleted column, and use EF 6 Code First for ORM. 我正在使用IsDeleted列在我的应用程序中实现软删除,并将EF 6 Code First用于ORM。 I want to filter deleted entities automatically when using dot operator for accessing lazy loading navigation properties (with many relationship).For example: a User has many Roles 我想在使用点运算符访问延迟加载导航属性(具有很多关系)时自动过滤已删除的实体。例如:一个用户具有多个角色

public class User
{
    private ICollection<Role> _roles;
    public virtual ICollection<Role> Roles
    {
        get { return _roles?? (_roles= new List<Role>()); }
        protected set { _roles= value; }
    }
}

and I need that when I use user.Roles, it will auto filter deleted entities, so I won't write it explicitly like because it will happen at many places: 而且我在使用user.Roles时需要它会自动过滤已删除的实体,因此我不会像在很多地方那样显式地编写它:

user.Roles.where(u => u.IsDeleted == false).ToList();

I'm thinking about EF Interceptor, but it would apply for all queries and I still want to load deleted entities in some places because of business requirement. 我正在考虑EF拦截器,但是它将适用于所有查询,并且由于业务需求,我仍然想在某些地方加载已删除的实体。 Is there any other way to achieve this efficiently? 还有其他方法可以有效地实现这一目标吗?
Thank you. 谢谢。

You can just add a "more proper" property to encapsulate the logic: 您可以添加一个“更合适的”属性来封装逻辑:

public class User
{
    private ICollection<Role> _roles;
    public virtual ICollection<Role> Roles
    {
        get { return _roles ?? (_roles = new List<Role>()); }
        protected set { _roles = value; }
    }

    public IEnumerable<Role> ActiveRoles
    {
        get { return this.Roles.Where(u => !u.IsDeleted); }
    }
}

Usage: 用法:

IEnumerable<Role> roles = user.ActiveRoles; // easy
  • I am assuming your objects ultimately implement some IDeletable or something. 我假设您的对象最终实现了一些IDeletable之类的东西。
    This was omitted 省略了

You may also consider implementing an extension method IEnumerable<IDeletable> Active() and the clutter will be moved to the usage part: user.Roles.Active() . 您还可以考虑实现扩展方法IEnumerable<IDeletable> Active() ,并且杂乱无章将移至用法部分: user.Roles.Active() Can't really tell which approach will be more elegant for your case. 真的无法确定哪种方法对您的情况而言会更优雅。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM