我在下面有通用存储库。我也有一个名为Queue的实体框架类,它映射到数据库。目的是使用在QueueTable的API中实现存储库。
基本存储库:
public class BaseRepository<T, TPrimaryKey> : IRepository<T, TPrimaryKey> where T : class, IEntity<TPrimaryKey>
{
protected readonly DbContext _context;
protected virtual DbSet<T> Table { get; }
protected IQueryable<T> All => Table.AsNoTracking();
public BaseRepository(DbContext context)
{
_context = context;
Table = _context.Set<T>();
}
public IQueryable<T> GetAll()
{
return All;
}
public async Task DeleteAsync(T entity)
{
await Task.FromResult(_context.Set<T>().Remove(entity));
}
通用存储库:
public interface IRepository<T, TPrimaryKey> where T : IEntity<TPrimaryKey>
{
IQueryable<T> GetAll();
DeleteAsync(T entity);
............
模型
public class Queue
{
public Queue()
{
QueueHistory = new HashSet<QueueHistory>();
}
public int QueueId { get; set; }
public int? QueueStatusId { get; set; }
public int? OriginalDepartmentId { get; set; }
public int? CreatedByUserId { get; set; }
public int? ObjectType { get; set; }
public int? ObjectId { get; set; }
IEntity:
public interface IEntity<TPrimaryKey>
{
[NotMapped]
TPrimaryKey Id { get; set; }
}
public interface IEntity : IEntity<int>
{
}
API:
在尝试在API Controller中声明存储库时,声明了这一点
public class QueuesController : ControllerBase
{
private readonly AssessmentContext _context;
public Queue queue = new Queue();
public BaseRepository<Queue,QueueId> queueRepository;
错误:
The type .Entities.Queue' cannot be used as type parameter 'T' in the generic type or method 'BaseRepository<T, TPrimaryKey>'. There is no implicit reference conversion from 'DomainModels.Entities.Queue' to 'Interfaces.IEntity<QueueId>'.
尝试进行转换会产生问题。
我该如何解决该错误?
答案 0 :(得分:3)
我认为您遇到的问题是了解类型约束的工作原理,您正在寻找的大致框架(使编译器满意)是这样的,我将实际实现留给您:)
请注意,我重新制作了一些类/接口,您可以使用从EF获得的IEntity,例如:
public interface IEntity<T>
{
T Id {get;set;}
}
public interface IRepository<T, TPrimaryKey> where T: IEntity<TPrimaryKey>{}
public class BaseRepository<T, TPrimaryKey> : IRepository<T, TPrimaryKey> where T: class, IEntity<TPrimaryKey>{}
public class Queue : IEntity<int>
{
public int Id {get;set;}
}
public class QueueRepository : BaseRepository<Queue, int>
{
}
public class QueueController
{
//Not a good idea
private readonly BaseRepository<Queue, int> queueRepository;
//Better
private readonly QueueRepository _queueRepository;
}