我想知道以下情况是否可能: 我创建了一个通用存储库来处理多个实体上的CRUD操作。鉴于我对实体具有软删除实现,对于与其他实体相关联的某个实体,我想基于一个属性(例如IsDeleted)过滤所包含的实体。
public abstract class Repository<T, TOrderBy> where T : BaseEntity
{
...
protected IQueryable<T> Get(Expression<Func<T, bool>> filter = null,
params Expression<Func<T, object>>[] includes)
{
var query = Set.AsQueryable();
if (filter != null)
{
query = query.Where(x => !x.DeletedAt.HasValue).Where(filter);
}
if (includes != null)
{
foreach (var include in includes)
{
query = query.Include(include); // In here i would like to also filter the included entities based on the IsDeleted property
}
}
return query;
}
}
BaseEntity类看起来像这样,所有类(包括我想在Include方法中过滤的类)都继承自它:
public abstract class BaseEntity
{
public bool IsDeleted { Get; Set; }
}
我知道可以在具体实体可用的级别上过滤包含的实体,但是我想知道在通用存储库类上是否可以这样做,因此我不需要为每个查询检查IsDeleted属性在特定的存储库中。
谢谢。
答案 0 :(得分:0)
假设您有两个类Foo
和FooContainer
,如下所示:
public class Foo : BaseEntity
{
public int Id { get; set; }
}
public class FooContainer : BaseEntity
{
public int Id { get; set; }
public virtual Foo Foo { get; set; }
}
和一个仓库:
public class FooContainerRepository : Repository<FooContainer, object>
{
public IQueryable<FooContainer> GetFooContainers(Expression<Func<FooContainer, bool>> filter = null,
params Expression<Func<FooContainer, object>>[] includes) => base.Get(filter, includes);
}
为了获得包含FooContainer
的{{1}}个实体,您可以这样调用存储库:
Foo
继续使用 var repo = new FooContainerRepository();
repo.GetFooContainers(null, fc => fc.Foo);
类中的Get
方法:
Repository
包括注释-至此,您只知道 foreach (var include in includes)
{
query = query.Include(include); // *include coment*
}
是Func,即以include
作为参数并返回FooContainer
。即使您知道该对象具有object
标志,它仍然只是一个IsDeleted
-这意味着使用当前的object
方法签名,不可能将Get
过滤添加到实体。
为此,您必须为每个包含的实体提供Where