I am working with EF Core and I created a generic repository. I have a method which returns all the entities with their child entities. Here is my method:
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();
}
While using this method I don't want to get the soft deleted data. I can filter the parent entity by writing where expression but I also want to do the same for the child entities. Currently I can handle the issue in controller like this:
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();
}
What I want is to do this filtering in my generic repository method. Is there any way to do it?
I'm not sure if I got your problem exactly. But here below is a sample code I used in one generic repository may help you.
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));
}
However, In the constructor, I didn't use Table. Instead I used as the following
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> ();
}
}
I hope it helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.