Dilshod K
Dilshod K

Reputation: 3032

How to create anonymous object from T?

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

Upvotes: 1

Views: 993

Answers (2)

er-sho
er-sho

Reputation: 9771

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;

Upvotes: 2

ahmeticat
ahmeticat

Reputation: 1939

You can use Repository pattern for this issue.

Create Repository class like ;

public class Repository<T> where T : class
{
    private readonly DbContext _dbContext;
    private readonly DbSet<T> _dbSet;

    public Repository(DBContext dbContext)
    {
        _dbContext = dbContext;
        _dbSet = dbContext.Set<T>();
    }


    public IQueryable<T> GetAll()
    {
        return _dbSet;
    }
}

and your function can be

 public object GetEntities<T>() 
 {
     using (DBContext db = new DBContext())
     {
            Repository<T> repository = new Repository<T>(db);
            list = repository.GetAll();
            return list.ToList();
     }
 }

Upvotes: 0

Related Questions