问题
I am using entity framework code first approach, and I am building a generic Repository class that provides data access. In this class I want an Add(T entity)
method. However, there is no InsertOnSubmit
method as part of the DbSet<T>
class, and if I try to use the Add
method, I get a compile time error:
The type 'TEntity' must be a reference type in order to use it as parameter 'TEntity' in the generic type or method 'System.Data.Entity.DbContext.Set<TEntity>()'
This is the method:
public TEntity Add(TEntity entity)
{
return _database.Set<TEntity>().Add(entity);
}
Anyone know a way to get around this?
Thanks
回答1:
Add a generic constraint to your repository class:
public class Repository<TEntity> where TEntity : class
回答2:
I have literally just posted this question but I have found a way around the problem - use the Set(Type t) method instead of the generic version like so:
public TEntity Add(TEntity entity)
{
return (TEntity)_database.Set(typeof(TEntity)).Add(entity);
}
A little bit of intellisense inspection goes a long way! Hope this helps someone...
来源:https://stackoverflow.com/questions/5621253/insertonsubmit-equivalent-in-dbcontext-dbset-using-entity-framework-4-code-first