We want to create a generic function which will select only required columns rather than returning the whole entity. For example I have a Country class which has the following properties.
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CountryId { get; set; }
[Required]
public string Name { get; set; }
public int CreatedBy {get;set;}
public DateTime CreatedDate {get;set;}
And I have a Respiratory Class which is common for all entities.
public class Repository<T> : IRepository<T> where T : class
{
DbContext db;
DbSet<T> currentEntity;
public Repository(DbContext db)
{
this.db = db;
currentEntity = db.Set<T>();
}
public void Add(T TEntity)
{
currentEntity.Add(TEntity);
}
public virtual List<T> GetAll()
{
return currentEntity.ToList<T>();
}
}
As GetAll
method is returning all columns, but I want to select only Name
and CountryId
. How can I create a generic function which would be returning only required data?
First you need added generic method in to generic repository:
public class Repository<T> : IRepository<T> where T : class
{
DbContext db;
DbSet<T> currentEntity;
public Repository(DbContext db)
{
this.db = db;
currentEntity = db.Set<T>();
}
public void Add(T TEntity)
{
currentEntity.Add(TEntity);
}
public virtual List<T> GetAll()
{
return currentEntity.ToList<T>();
}
public ICollection<TType> Get<TType>(Expression<Func<T, bool>> where, Expression<Func<T, TType>> select) where TType : class
{
return currentEntity.Where(where).Select(select).ToList();
}
}
now, you can called this method. Example:
public void SomeService()
{
var myData = Repository.Get(x => x.CountryId > 0, x => new { x.CountryId, x.Name });
foreach (var item in myData)
{
var id = item.CountryId;
var name = item.Name;
// ...
}
}
And last - you need runtime create lambda expression and runtime get Required fields. Maybe this post help you : Create a lambda expression with a new anonymous type at runtime, and How do I read an attribute on a class at runtime? p.s. sory for my bad english =)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With