【问题标题】:Generic Repository for Lookup Values查找值的通用存储库
【发布时间】:2014-06-30 10:10:34
【问题描述】:

我在数据库中有一堆查找实体(总共大约 10 个),它们都实现了以下接口

interface ILookupValue
{
    int Id { get; set; }
    string Name { get; set; }
    string Description { get; set; }
}

目前,我为每个实现 ILookupRepository 接口的实体都有一个存储库

public interface ILookupRepository<T> where T : class
{
    IEnumerable<T> GetLookupData();
}

示例实现

public class CustomerRepository : ILookupRepository<Customer>
{
    public IDbContext _context;

    public CustomerRepository(IDbContext context)
    {
        context = _context;
    }

    public IEnumerable<Customer> GetLookupData()
    {
        return _context.Set<Customer>();
    }
}

我预计任何存储库都不需要任何其他方法,那么有没有一种方法可以为这种情况创建一个通用存储库,而不必为每种查找类型使用额外的代码连接存储库?

编辑:基于 Dennis_E 的回答,这就是我想要的

 public class LookupRepository<T> : ILookupRepository<T> where T :  class, ILookupValue
{
    public IDbContext _context;

    public LookupRepository(IDbContext context)
    {
        context = _context;
    }

    public IEnumerable<T> GetLookupData()
    {
        return _context.Set<T>();
    }

}

【问题讨论】:

  • 您也应该将ILookupValue 约束放在ILookupRepository

标签: c# .net entity-framework generics


【解决方案1】:

这个类对我来说看起来很普通。

public class LookupRepository<T> : ILookupRepository<T>
{
    public IDbContext _context;

    public LookupRepository(IDbContext context)
    {
       context = _context;
    }

    public IEnumerable<T> GetLookupData()
    {
        return _context.Set<T>();
    }
}

然后用new LookupRepository&lt;Customer&gt;();实例化

【讨论】:

    【解决方案2】:

    您将需要一个通用基类,然后让您的 CustomerRepository 继承自该基类:

    public class GenericRepository<T> : ILookupRepository<T>
    {
        protected readonly IDbContext _context;
    
        protected GenericRepository(IDbContext context)
        {
            _context = context;
        }
    
        public IEnumerable<T> GetLookupData()
        {
            return _context.Set<T>();
        }
    }
    

    然后您可以直接创建GenericRepository&lt;Customer&gt; 的实例,或者如果您愿意,可以让您的 IoC 容器为您注入该依赖项。

    【讨论】:

      【解决方案3】:

      它看起来很通用,但当您需要一次性使用 DB 的连接语句时,一种方法可能会派上用场。

      返回 IQueryable

      【讨论】:

      • 这有点可疑。可以说,它表示数据访问问题可能会从他们的层泄漏(假设他们有一个)。我想说这可能只在必要时才这样做。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-10
      • 2016-01-09
      • 1970-01-01
      • 2017-10-27
      • 2012-01-01
      相关资源
      最近更新 更多