Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select specific columns in a generic repository function

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?

like image 970
Shival Avatar asked Jun 24 '17 19:06

Shival


1 Answers

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 =)

like image 199
Alexander Brattsev Avatar answered Sep 18 '22 19:09

Alexander Brattsev