Create generic abstract class using EF database first approach

会有一股神秘感。 提交于 2020-01-17 07:15:10

问题


I have some similar entities and I want to create a generic abstract class for CRUD operations for them, but I don't know how can access to entities in generic class. For example:

public abstract class HeaderRepository<T>
{
    public HeaderRepository()
    {

    }

    public virtual byte[] Insert(T item)
    {
        using (MyEntities context = new MyEntities())
        {
            context.*****  <-- What I should write to add an object to entity T
        }
    }
}

I hope I've got it.


回答1:


You need to set your DB set. It would be better to have a private variable at class level, set in the constructor and then use it.

using (MyEntities context = new MyEntities())
    {
        DbSet<T> dbSet = context.Set<T>();
        dbSet.Add(...) //Whatever your operation is. 
    }


来源:https://stackoverflow.com/questions/45673032/create-generic-abstract-class-using-ef-database-first-approach

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!