I have GetEntities method in EF context. In some cases I don't want to load all properties of entities in memory. I want to load only 'selected' properties. I'm using anonymous object for getting only special properties. For example, I have Product entity and I'm getting only Name and Cost properties (ONLY FOR READING).
context.GetEntities<Product>().Select(a => new { a.Name,a.Cost }).ToList();
I'm using it in many places. So, I created PropertyNames collection and I want to create GetEntities method which gets entities with these properties:
public object GetEntities<T>(IEnumerable<string> proeprtyNames)
{
return //anonymous entities which have only proeprtyNames properties
}
How to create this method? And also I don't know what should be return type of method
1) You need to create a repository to accept your TEntity
as a generic class entity and in that repository, you have to create one method that can retrieve only those columns from the database table that you're specified in Select
expression predicate.
public class Repository<TEntity> where TEntity : class
{
private readonly DbContext _context;
public Repository(DbContext context)
{
_context = context;
}
public List<TResult> GetEntities<TResult>(Expression<Func<TEntity, TResult>> selector) where TResult : class
{
return _context.Set<TEntity>().Select(selector).ToList();
}
}
2) And then while using above repository, you can pass only those properties from your Product
entity those you want to retrieve like
Repository<Product> repository = new Repository<Product>(new MySqlDbContext());
var anonymousResultSet = repository.GetEntities(x => new { x.Name, x.Cost }); //<= Here you can specify those columns that you want to retrieve.
return anonymousResultSet;