我们想要创建一个通用函数,它将只选择所需的列而不是返回整个实体。例如我有一个 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
。如何创建一个仅返回所需数据的通用函数?
最佳答案
首先,您需要将通用方法添加到通用存储库中:
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? 附:抱歉我的英语不好 =)
关于c# - 在通用存储库函数中选择特定列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44740065/