简体   繁体   English

首先使用Entity Framework 4代码在DbContext.DbSet中插入等效的InsertOnSubmit

[英]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.

相关问题 宣布DBSet <Type> 在DBcontext中 - 实体框架代码优先 - Declaring DBSet<Type> within DBcontext - Entity Framework Code First Entity Framework等效于InsertonSubmit - Entity Framework equivalent of InsertonSubmit 实体框架中DBContext,DBSet &lt;&gt;的引用 - References for DBContext, DBSet<> in Entity Framework 实体框架代码首先添加 DbSet 属性 - Entity Framework code first adding DbSet property 如何首先使用实体​​框架代码在DbContext中使用ConnectionString? - How to use ConnectionString with DbContext using Entity Framework code first? 在Code第一实体框架中将DbContext转换为Datatable - Convert DbContext to Datatable in Code first entity framework 使用包含条件的实体代码第一个DbSet - Entity Code First DbSet using include with conditions 有条件地在不同的DbContext.DbSet(作为模板参数)之间进行选择? - Conditionally select between different DbContext.DbSet (as template-parameter)? DbContext - > DbSet - >缺少Where子句(Entity Framework 6) - DbContext -> DbSet -> Where clause is missing (Entity Framework 6) 在Entity Framework中使用代码优先dbcontext进行选择时出现EntitySqlException - EntitySqlException on select with code first dbcontext in Entity Framework
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM