C
C#2y ago
sonodan.

EF Core - Generic repository update method

I have a generic repository which contains my general CRUD operations interacting with my DbContext. I have an Update method which updates the Entity in the dbSet based on the new values. The TEntity is a class which has a property that depends on another custom class. When I call this function, all TEntity properties are updated except these navigation properties. Is there a way to generically add Include and take an argument of properties to include?
public void Update(TEntity entity)
{
_dbSet.Update(entity);
}
public void Update(TEntity entity)
{
_dbSet.Update(entity);
}
For extra context, I was able to do something similar on my Get methods, but unsure how this really would applied to update:
public async Task<IEnumerable<TEntity>> GetAsync(Expression<Func<TEntity, bool>>? filter = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>>? orderBy = null, params string[] includes)
{
var query = _dbSet.AsQueryable();

query = includes.Aggregate(query, (current, include) => current.Include(include));

if (filter != null)
query = query.Where(filter);

var result = orderBy != null ? (await orderBy(query).ToListAsync()) : (await query.ToListAsync());

return result;
}
public async Task<IEnumerable<TEntity>> GetAsync(Expression<Func<TEntity, bool>>? filter = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>>? orderBy = null, params string[] includes)
{
var query = _dbSet.AsQueryable();

query = includes.Aggregate(query, (current, include) => current.Include(include));

if (filter != null)
query = query.Where(filter);

var result = orderBy != null ? (await orderBy(query).ToListAsync()) : (await query.ToListAsync());

return result;
}
1 Reply
Saber
Saber2y ago
yeah the easy way to do it is to delete your generic repository and just use ef