InsertOnSubmit equivalent in DbContext.DbSet using Entity Framework 4 code first

陌路散爱 提交于 2019-12-19 06:08:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!