我想知道以下情况是否可能:我创建了一个通用回购,用于处理多个实体上的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属性。
谢谢。
假设您有两个类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);
}
为了获得包含Foo
的FooContainer
实体,您可以这样调用回购:
var repo = new FooContainerRepository();
repo.GetFooContainers(null, fc => fc.Foo);
转到Repository
类中的Get
方法:
foreach (var include in includes)
{
query = query.Include(include); // *include coment*
}
include-comment-在这一点上,您只知道include
是Func,即FooContainer
作为参数并返回object
。即使您知道该对象具有IsDeleted
标志,但它仍然只是一个object
——这意味着使用当前的Get
方法签名,不可能将Where
过滤添加到包含的实体中。
为了做到这一点,您必须为每个包含的实体提供Expression<Func<T, bool>> includeFilter