如何从 T 创建匿名对象?

How to create anonymous object from T?

我在 EF 上下文中有 GetEntities 方法。在某些情况下,我不想在内存中加载实体的所有属性。我只想加载 'selected' 属性。我使用匿名对象来获取特殊属性。例如,我有 Product 实体,但我只获得 Name 和 Cost 属性(仅供阅读)。

context.GetEntities<Product>().Select(a => new { a.Name,a.Cost }).ToList();

我在很多地方都在使用它。因此,我创建了 PropertyNames 集合,我想创建 GetEntities 方法来获取具有这些属性的实体:

 public object GetEntities<T>(IEnumerable<string> proeprtyNames) 
 {
     return //anonymous entities which have only proeprtyNames properties
 }

如何创建这个方法?而且我也不知道 return 类型的方法

应该是什么

您可以使用 Repository pattern 解决此问题。

创建 Repository class 赞;

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;
    }
}

你的函数可以是

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

1) 您需要创建一个存储库以接受您的 TEntity 作为通用 class 实体,并且在该存储库中,您必须创建一个方法只能从数据库 table 中检索您在 Select 表达式谓词中指定的那些列。

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) 然后在使用上面的存储库时,您可以仅传递 Product 实体中您想要检索的那些属性

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;