I am using the example here to create a repository pattern with Unit of Work.
Within the code, there is a generic Get method:
public class GenericRepository<TEntity> where TEntity : class
{
internal AdminDbContext context;
internal DbSet<TEntity> dbSet;
public GenericRepository(AdminDbContext context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
}
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<TEntity, TEntity> selector = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
foreach (var includeProperty in includeProperties.Split
(new char[] { ','}, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
else
{
return query.ToList();
}
}
At this moment when this method is called, all the records from the database are fetched and column selection is done in memory.
My question is how can I extend the Get method here that would allow me to dynamically pass column names to this method so that only the desired columns are selected at database level?
I have tried:
- Accepting a string parameter with the comma seperated values of the desired columns but that I could not map them to the entity.
- Creating a parameter with the same type of filter which gave an error.