问题
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