c# - 在通用存储库函数中选择特定列

标签 c# linq repository-pattern

我们想要创建一个通用函数,它将只选择所需的列而不是返回整个实体。例如我有一个 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 方法返回所有列,但我只想选择 NameCountryId。如何创建一个仅返回所需数据的通用函数?

最佳答案

首先,您需要将通用方法添加到通用存储库中:

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/

相关文章:

ASP.NET 存储库模式/服务层缓存

asp.net-mvc-3 - 使用 Autofac 进行 MVC 3 通用存储库注入(inject)

c# - Entity Framework 模型优先设计中的存储库模式

c# - 客户关系管理 2011 : Limitation of query expression?

c# - Linq 隐式转换为类型

sql-server - NHibernate 选择前 N 个,条件是使用 fetch 的子项

c# - 如何使用 Linq 确定 List<T> 中的所有对象是否具有相同的属性值

javascript - 为什么具有许多有效数字的数字在 C# 和 JavaScript 中的处理方式不同?

c# - 如何测量 C# 中给定进程的 CPU 周期?

c# - outputLocation 不是有效的 S3 路径。雅典娜异常(exception)