I've got a DbContext child class that talks to the Database through entity framework. I'm using MVC C#.
I've got n DbSets related to my tables. I want to invoke the Add method for any DbSet.Add(entityObject), in this case UserAccounts.Add(entityUserAccount) using reflections or dynamic variable.
I'm doing this because I need to inject DbContect by dependency injection in my controllers.
public class DataContext: DbContext
{
public DbSet<UserAccount> UserAccounts { get; set; }
public void Insert<TypeEntity>(TypeEntity entity) where TypeEntity : BaseEntity
{
var typesToRegister = typeof(DataContext).GetProperties().
Where(p => p.PropertyType == typeof(DbSet<TypeEntity>));
//This is where the code explodes in face:-)
//Please let me know how to fix it
var dbSetItem = typesToRegister.First();
var methodAdd = dbSetItem.GetType().GetMethod("Add");
methodAdd.Invoke(this, new TypeEntity[] { entity });
}
}
//Insert<TypeEntity>(TypeEntity entity) is my service
//method to invoke the DbSet<T>.Add() method.
Aucun commentaire:
Enregistrer un commentaire