简体   繁体   中英

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. 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

向存储库类添加通用约束:

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:

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM