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

后端 未结 3 1185
春和景丽
春和景丽 2021-02-06 10:25

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
{
    ...

    publi         


        
3条回答
  •  后悔当初
    2021-02-06 10:53

    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 i.e. use where TEntity : Entity instead of where TEntity : class

    public abstract class Entity where TEntity : Entity
    {
        protected DbContext _dbContext;
    
        protected Entity()
        {
            this._dbContext = new SMTDBContext();
        }
    
        public void Add()
        {
            this._dbContext.Set().Add((TEntity)this);
            this._dbContext.SaveChanges();
        }
    }
    

提交回复
热议问题