![](/img/trans.png)
[英]EF Core - How to Include child but limit the number of child entities returned
[英]EF Core filter the child entities after include
我正在使用 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 表達式來過濾父實體,但我也想對子實體做同樣的事情。 目前我可以像這樣處理 controller 中的問題:
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();
}
我想要的是在我的通用存儲庫方法中進行此過濾。 有什么辦法嗎?
我不確定我是否確實遇到了您的問題。 但下面是我在一個通用存儲庫中使用的示例代碼可能會對您有所幫助。
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> ();
}
}
我希望它有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.