基本上,我想实现一个存储库,即使通过导航属性也可以过滤所有软删除记录。所以我有一个基本实体,类似这样:
public abstract class Entity
{
public int Id { get; set; }
public bool IsDeleted { get; set; }
...
}
Run Code Online (Sandbox Code Playgroud)
和一个存储库:
public class BaseStore<TEntity> : IStore<TEntity> where TEntity : Entity
{
protected readonly ApplicationDbContext db;
public IQueryable<TEntity> GetAll()
{
return db.Set<TEntity>().Where(e => !e.IsDeleted)
.InterceptWith(new InjectConditionVisitor<Entity>(entity => !entity.IsDeleted));
}
public IQueryable<TEntity> GetAll(Expression<Func<TEntity, bool>> predicate)
{
return GetAll().Where(predicate);
}
public IQueryable<TEntity> GetAllWithDeleted()
{
return db.Set<TEntity>();
}
...
}
Run Code Online (Sandbox Code Playgroud)
InterceptWith 函数来自此项目:https://github.com/davidfowl/QueryInterceptor和https://github.com/StefH/QueryInterceptor(与异步实现相同)
an 的用法IStore<Project>如下:
var project …Run Code Online (Sandbox Code Playgroud)