Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 616
jcvandan Avatar asked Apr 11 '11 12:04

jcvandan


People also ask

What is the difference between DbSet and DbContext?

Intuitively, a DbContext corresponds to your database (or a collection of tables and views in your database) whereas a DbSet corresponds to a table or view in your database.

What is DbSet in Entity Framework C#?

A DbSet represents the collection of all entities in the context, or that can be queried from the database, of a given type. DbSet objects are created from a DbContext using the DbContext. Set method.

How do I use code first in Entity Framework?

As clear from the figure, the entity framework creates or updates the database depending upon the domain classes. Hence, the user needs to code first, and then the entity framework will create the database using the code. That is why it is called the code first approach.


1 Answers

Add a generic constraint to your repository class:

public class Repository<TEntity> where TEntity : class
like image 135
Diego Mijelshon Avatar answered Oct 22 '22 03:10

Diego Mijelshon