[英]Generic Repository for Lookup Values
I have a bunch of Lookup Entities in the database (About 10 in total) that all implement the following interface 我在数据库中有一堆查找实体(总共约10个),都实现了以下接口
interface ILookupValue
{
int Id { get; set; }
string Name { get; set; }
string Description { get; set; }
}
At the moment i have a repository for each entity that implements an ILookupRepository interface 目前,我为每个实现ILookupRepository接口的实体都有一个存储库
public interface ILookupRepository<T> where T : class
{
IEnumerable<T> GetLookupData();
}
Example Implementation 示例实施
public class CustomerRepository : ILookupRepository<Customer>
{
public IDbContext _context;
public CustomerRepository(IDbContext context)
{
context = _context;
}
public IEnumerable<Customer> GetLookupData()
{
return _context.Set<Customer>();
}
}
I don't anticipate any of the repositories needing any other methods, so is there a way of making a generic repository for this scenario without having to have have additional code wiring up repository for each lookup type? 我不认为任何存储库都需要任何其他方法,因此是否有一种方法可以针对这种情况创建通用存储库,而不必为每种查找类型都需要额外的代码来连接存储库?
Edit: based on Dennis_E's answer, this is what i'm going with 编辑:基于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>();
}
}
The class looks pretty generic to me. 对我来说,这堂课看起来很普通。
public class LookupRepository<T> : ILookupRepository<T>
{
public IDbContext _context;
public LookupRepository(IDbContext context)
{
context = _context;
}
public IEnumerable<T> GetLookupData()
{
return _context.Set<T>();
}
}
Then instantiate with new LookupRepository<Customer>();
然后用
new LookupRepository<Customer>();
实例化new LookupRepository<Customer>();
You will need a generic base class and then have your CustomerRepository
inherit from that: 您将需要一个通用基类,然后让您的
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>();
}
}
Then you can create an instance of GenericRepository<Customer>
directly, or if you prefer, have your IoC container inject that dependency for you. 然后,您可以直接创建
GenericRepository<Customer>
的实例,或者,如果愿意,可以让IoC容器为您注入依赖项。
It looks generic, though one method might come handy when you need to make join statements hitting DB in one go. 它看起来很通用,但是当您需要使连接语句一口气击中数据库时,一种方法可能会派上用场。
One that returns IQueryable 一个返回IQueryable的代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.