我正在使用EF Core,并创建了一个通用存储库。我有一个返回所有实体及其子实体的方法。这是我的方法:
public Repository(DevbAERPContext dbContext)
{
_dbContext = dbContext;
Table = _dbContext.Set<T>();
}
public async Task<IEnumerable<T>> GetAllWithInclude(Expression<Func<T, bool>> where, string[] includeProperties)
{
var result = includeProperties.Aggregate(Table.Where(where), (query, path) => query.Include(path)).AsNoTracking();
return await result.ToListAsync();
}
使用此方法时,我不想获取软删除的数据。我可以通过编写where表达式来过滤父实体,但是我也想对子实体做同样的事情。目前,我可以在控制器中处理此类问题:
var roles = await _roleRepository.GetAllWithInclude(x => !x.IsDeleted, new string[] { "RoleTemplateSkills", "RoleTemplateSkills.Skill" }).ConfigureAwait(false);
var mappedRoles = _mapper.Map<List<RoleTemplateViewModel>>(roles);
foreach(var mappedRole in mappedRoles)
{
mappedRole.RoleTemplateSkills = mappedRole.RoleTemplateSkills.Where(x => !x.IsDeleted).ToList();
}
我想要在我的通用存储库方法中执行此过滤。有什么办法吗?
答案 0 :(得分:0)
我不确定我是否确实遇到了您的问题。但是下面是我在一个通用存储库中使用的示例代码,可能会对您有所帮助。
public TEntity FindByInclude(Expression<Func<TEntity, bool>> predicate, params Expression<Func<TEntity, object>>[] includeProperties)
{
IQueryable<TEntity> result = dbSet.Where(predicate);
if (includeProperties.Any())
{
foreach (var includeProperty in includeProperties)
{
result = result.Include(includeProperty);
}
}
var firstResult = result.FirstOrDefault(predicate);
if (firstResult != null)
dbSet.Attach(firstResult);
return firstResult;
}
public IEnumerable<TEntity> GetAllIncluding(params Expression<Func<TEntity, object>>[] includeProperties)
{
IQueryable<TEntity> result = dbSet.AsNoTracking();
return includeProperties.Aggregate(result, (current, includeProperty) => current.Include(includeProperty));
}
但是,在构造函数中,我没有使用Table。相反,我用作以下
public class FitnessRepository<TEntity> : IFitnessRepository<TEntity> where TEntity :class {
private readonly FitnessDbContextt fitnessDbContext;
private readonly DbSet<TEntity> dbSet;
public FitnessRepository (FitnessDbContextt context) {
fitnessDbContext = context;
dbSet = context.Set<TEntity> ();
}
}
我希望它会有所帮助。
答案 1 :(得分:0)