我创建了一个接口,其中包含以下方法(GetAll,GetById,CreateAsync ...等(在菱形符号中,我告诉你它是 T 的存储库,其中 T 是一个类,因此您可以为任何具有
IGENERIC存储库.CS:
public interface IGenericRepository<T> where T : class
{
IQueryable<T> GetAll();
Task<T> GetByIdAsync(int id);
Task<T> CreateAsync(T entity);
Task<T> UpdateAsync(T entity);
Task DeleteAsync(T entity);
Task<bool> ExistAsync(int id);
}
但是在实现接口时,在一个名为 GenericRepository 的类中.cs它告诉我一个不一致的错误,我附加了我的 GenericRepository.CS 类
GENERICREPOSTITORY.CS:
public class GenericRepository<T> : IGenericRepository<T> where T : class, IEntity
{
private readonly DataContext context;
public GenericRepository(DataContext context)
{
this.context = context;
}
public IQueryable<T> GetAll()
{
return this.context.Set<T>().AsNoTracking();
}
public async Task<T> GetByIdAsync(int id)
{
return await this.context.Set<T>()
.AsNoTracking()
.FirstOrDefaultAsync(e => e.Id == id);
}
public async Task<T> CreateAsync(T entity)
{
await this.context.Set<T>().AddAsync(entity);
await SaveAllAsync();
return entity;
}
public async Task<T> UpdateAsync(T entity)
{
this.context.Set<T>().Update(entity);
await SaveAllAsync();
return entity;
}
public async Task DeleteAsync(T entity)
{
this.context.Set<T>().Remove(entity);
await SaveAllAsync();
}
public async Task<bool> ExistAsync(int id)
{
return await this.context.Set<T>().AnyAsync(e => e.Id == id);
}
public async Task<bool> SaveAllAsync()
{
return await this.context.SaveChangesAsync() > 0;
}
}
错误如下:
可访问性不一致:约束类型"IEntity"比"通用存储库"更难访问
我做错了什么?为什么我不能实现 GenericRepostory.cs 类?我想我以正确的方式拥有所有用途和遗产,对我有什么帮助吗?
这就是原因类型IEntity
是用非公共访问修饰符声明的,而GenericRepository<T>
是public
<</p>
约束类型"IEntity"的可访问性低于 '通用存储库
">
这意味着IEntity
没有与GenericRepository<T>
相同(或更广泛(的可访问性。编译器给出此错误是因为它会导致不一致,例如,如果您甚至无法创建要传递给它的IEntity
,您将如何调用您的UpdateAsync
?
要解决此问题,您可以IEntity
public
GenericRepository<T>
或将对的访问限制为与IEntity
相同的级别(例如internal
如果IEntity
标记为这样(,具体取决于您的预期用例。