我们想要创建一个通用函数,它只选择必需的列而不是返回整个实体。例如,我有一个Country类 具有以下属性。
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CountryId { get; set; }
[Required]
public string Name { get; set; }
public int CreatedBy {get;set;}
public DateTime CreatedDate {get;set;}
我有一个呼吸类,这对所有实体都很常见。
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>();
}
}
由于GetAll
方法返回了所有列,但我只想选择Name
和CountryId
。如何创建只返回所需数据的通用函数?
答案 0 :(得分:7)
首先,您需要在通用存储库中添加通用方法:
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();
}
}
现在,您可以调用此方法。例如:
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;
// ...
}
}
最后 - 您需要运行时创建lambda表达式和运行时获取必填字段。也许这篇文章可以帮助您:Create a lambda expression with a new anonymous type at runtime和How do I read an attribute on a class at runtime? 附:我的坏英语的索尼=)
答案 1 :(得分:-2)
声明DTO类:
public class Getdata
{
public int Id { get; set; }
public string Name { get; set; }
}
并且像这样使用..
public virtual List<Getdata> GetAll()
{
var countrys = db.currentEntity.ToList();
var data = (from f in countrys
select new Getdata
{
Id = f.CountryId,
Name = f.CountryName
}).ToList();
return data;
}