我正在尝试在我的应用程序中实现通用存储库模式。我有两个接口(interface),IEntity 和 IRepository:
实体:
public interface IEntity
{
int Id { get; set; }
}
IRepository:
public interface IRepository<T> where T : IEntity
{
void AddOrUpdate(T ent);
void Delete(T ent);
IQueryable<T> GetAll();
}
现在我正在尝试制作一个通用的 RepositoryGlobal 类,但我收到了这个错误:
The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method
我的代码是这样的:
public class RepositoryGlobal<T> : IRepository<T> where T : IEntity
{
public RepositoryGlobal(DbContext _ctx)
{
this._context = _ctx;
}
private DbContext _context;
public void Add(T ent)
{
this._context.Set<T>().Add(ent);
}
public void AddOrUpdate(T ent)
{
if (ent.Id == 0)
{
//not important
}else
{
//for now
}
}
public void Delete(T ent)
{
}
public IQueryable<T> GetAll()
{
return null;
}
}
错误出现在 RepositoryGlobal 类的 Add 方法中。 有任何想法吗? 谢谢
最佳答案
你需要添加一个class
约束
public class RepositoryGlobal<T> : IRepository<T> where T : class, IEntity
关于c# - 通用存储库问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38199058/