My Entityframework context :
public class MyContext : DbContext
{
public DbSet<Company> Companies { get; set; }
public DbSet<Contact> Contacts { get; set; }
public DbSet<Event> Events { get; set; }
}
My method to add objects :
public void AddObject(DbContext context, Type t, object object_to_add)
{
PropertyInfo context_property = context.GetType().GetProperties().Where(p => typeof(IEnumerable).IsAssignableFrom(p.PropertyType)
&& p.PropertyType.GenericTypeArguments.Any()
&& p.PropertyType.GenericTypeArguments.First() == t)
.Single();
DbSet db_set = (DbSet)context_property.GetMethod.Invoke(context, null);
db_set.Add(object_to_add);
}
But the code crashes when I try to cast a DbSet<> to DbSet,
I'm using reflection because I receive DTO objects that I map to an existing model(via reflection as well), I don't want to code an add method for each new model (I have like 40 and the list is exponentially growing)
Blockquote
Any solution?
Aucun commentaire:
Enregistrer un commentaire