首先使用Entity Framework 4代码在DbContext.DbSet中InsertOnSubmit等效 [英] InsertOnSubmit equivalent in DbContext.DbSet using Entity Framework 4 code first

查看:118
本文介绍了首先使用Entity Framework 4代码在DbContext.DbSet中InsertOnSubmit等效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用实体框架代码第一种方法,我正在构建一个提供数据访问的通用Repository类。在这个类中,我想要一个 Add(T entity)方法。但是,没有 InsertOnSubmit 方法作为 DbSet< T> 类的一部分,如果我尝试使用添加方法,我收到编译时错误:

  TEntity'必须是一个引用类型,以便在通用类型或方法'System.Data.Entity.DbContext.Set< TEntity>()'
中使用它作为参数'TEntity'

这是方法:

  public TEntity Add (TEntity entity)
{
return _database.Set< TEntity>()。Add(entity);
}

任何人都知道要解决这个问题吗?



谢谢

解决方案

将一般约束添加到您的存储库类中:

  public class Repository< TEntity>其中TEntity:class 


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

解决方案

Add a generic constraint to your repository class:

public class Repository<TEntity> where TEntity : class

这篇关于首先使用Entity Framework 4代码在DbContext.DbSet中InsertOnSubmit等效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆