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
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.