使用GetTable()给出错误'type T必须是引用类型'

时间:2013-11-27 10:47:10

标签: c# visual-studio-2010

我正在尝试使用GetTable()将我的存储库模式与EntityFramework一起添加一个通用的Insert方法(希望我的模式正确)

但我收到的错误如下面的评论所示。

我实际上想要在数据库中插入记录,而不管表的类型如何  任何帮助非常感谢:)

这是我的BaseRepository泛型类

public abstract class BaseRepository<T>
{
    private static DBEntities dbEntities;

     public BaseRepository()
    {
        dbEntities = new DBEntities();
    }
    public IQueryable GetTable<T>(T entity) where T : class
    {
    return dbEntities.CreateObjectSet<T>();
    }

public void Insert<T>(T obj)
{
    //the line below gives an error 'The Type T must be a reference type
    // in order to use it as parameter T. I HAVE tried adding ref here
    // and in GetTable method, but same error
    var table = GetTable(obj);        
    int saveChanges = dbEntities.SaveChanges();

}

}

1 个答案:

答案 0 :(得分:1)

尝试更改您的代码:

public abstract class BaseRepository<T> where T : class
{
    private static DBEntities dbEntities;

    public BaseRepository()
    {
        dbEntities = new DBEntities();
    }
    public IQueryable GetTable(T entity) 
    {
        return dbEntities.CreateObjectSet<T>();
    }

    public void Insert(T obj)
    {
       //the line below gives an error 'The Type T must be a reference type
       // in order to use it as parameter T. I HAVE tried adding ref here
       // and in GetTable method, but same error
       var table = GetTable(obj);        
       int saveChanges = dbEntities.SaveChanges();    
    }
}