[英]InsertOnSubmit equivalent in DbContext.DbSet using Entity Framework 4 code first
I am using entity framework code first approach, and I am building a generic Repository class that provides data access. 我正在使用实体框架代码第一种方法,我正在构建一个提供数据访问的通用Repository类。 In this class I want an
Add(T entity)
method. 在这个类中,我想要一个
Add(T entity)
方法。 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: 但是,作为
DbSet<T>
类的一部分,没有InsertOnSubmit
方法,如果我尝试使用Add
方法,则会出现编译时错误:
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 谢谢
向存储库类添加通用约束:
public class Repository<TEntity> where TEntity : class
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: 我刚刚发布了这个问题,但我找到了解决问题的方法 - 使用Set(Type t)方法而不是通用版本,如下所示:
public TEntity Add(TEntity entity)
{
return (TEntity)_database.Set(typeof(TEntity)).Add(entity);
}
A little bit of intellisense inspection goes a long way! 一点点intellisense检查有很长的路要走! Hope this helps someone...
希望这有助于某人......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.