Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use generic type with the database Context in EF6 Code First

For example, let say I have 4 different entity that each implement a Add() method that add the entity to the database :

public class Profile
{
    ...

    public void Add()
    {
        this._dbContext.Profile.Add(this);
        this._dbContext.SaveChanges();
    }

    ...
}

Now I would like to have a generic class that implement this kind of behavior in one abstract class instead of X number of classes. So I tried the following :

public abstract class Entity<TEntity> where TEntity : class 
{
    protected DbContext _dbContext;

    protected Entity()
    {
        this._dbContext = new SMTDBContext();
    }

    public void Add()
    {
        this._dbContext.Set<TEntity>().Add(this);
        this._dbContext.SaveChanges();
    }
}

Of course it doesnt worrk because "this" is not a TEntity... but it will be in the future! I tried searching for someone who did something similar without success so far.

like image 912
Zwik Avatar asked Jun 05 '14 19:06

Zwik


1 Answers

The solution to your problem is to be more explicit with the definition of the generic constraint. Define the constraint as TEntity must be a sub-class of Entity<TEntity> i.e. use where TEntity : Entity<TEntity> instead of where TEntity : class

public abstract class Entity<TEntity> where TEntity : Entity<TEntity>
{
    protected DbContext _dbContext;

    protected Entity()
    {
        this._dbContext = new SMTDBContext();
    }

    public void Add()
    {
        this._dbContext.Set<TEntity>().Add((TEntity)this);
        this._dbContext.SaveChanges();
    }
}
like image 165
qujck Avatar answered Oct 13 '22 00:10

qujck