c# - 通用存储库问题

标签 c# generics repository

我正在尝试在我的应用程序中实现通用存储库模式。我有两个接口(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/

相关文章:

git - 如何使用 GIT 从 Bitbucket 将所有存储库克隆到团队中

c# - 如何使用工作单元和存储库模式回滚事务?

c# - 如何在单独的线程上运行 Converter 内的代码,以便 UI 不卡住?

c# - 在只有 4.0 框架的机器上引用 2.0 库运行 .NET 4.0 应用程序

c# - 如何通过 WebRequest 调用 MVC 操作并通过 Active Directory 验证请求?

c# - 当参数实现通用接口(interface)时,NUnit 通用测试夹具不显示

c# - C# 中的泛型函数声明

java - 通用对象的 HashCode 实现

git - 使用 BFG repo-cleaner 后检查 git repo

c# - 如何取消屏蔽密码文本框并将其屏蔽回密码?