2013-11-27 67 views
0

我想添加一个通用的插入方法使用GetTable()与我的存储库模式与EntityFramework(希望我有模式的权利)使用GetTable()给出的错误'类型T必须是引用类型'

但是我收到下面的注释中显示的错误。

其实我是想在数据库中插入记录,而不管该表 任何帮助非常感谢:)

这是我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

1)如果该类具有泛型pe参数,您不应该在方法上重复该参数。 2)'T:class'约束需要在'BaseRepository '上,而不是在方法上。 – CodesInChaos

+0

“我已经尝试过在这里添加引用”,这意味着引用*类型*和引用*参数*之间的混淆,可以通过详细阅读[参数传入C#](http://www.yoda .arachsys.com/csharp/parameters.html) – AakashM

回答

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();  
    } 
} 
+0

这工作。我不应该在方法名称旁边放置< T >:D thx –

相关问题