简体   繁体   中英

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. 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.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. 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.
    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() . Can't really tell which approach will be more elegant for your case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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