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
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.
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.
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.
Add a generic constraint to your repository class:
public class Repository<TEntity> where TEntity : class
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With