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

后端 未结 3 1187
春和景丽
春和景丽 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:44

    You could get around that be the following; you just have to make sure at runtime it really is a TEntity:

    public void Add()
    {
        object obj = this;
        this._dbContext.Set().Add((TEntity)obj);
        this._dbContext.SaveChanges();
    }
    

    Since the compiler loses track of what this is when you use an object type. If you get an error, it's because obj is not truly a TEntity. However, you may want to use a factory, repository, or other design pattern for working with the entity framework DBSet.

提交回复
热议问题