c# - Invoking DbSet<Type>.Add() method using reflections, in a child class of DbContext -
i've got dbcontext child class talks database through entity framework. i'm using mvc c#.
i've got n dbsets related tables. want invoke add method dbset.add(entityobject), in case useraccounts.add(entityuseraccount) using reflections or dynamic variable.
i'm doing because need inject dbcontect dependency injection in controllers.
public class datacontext: dbcontext { public dbset<useraccount> useraccounts { get; set; } public void insert<typeentity>(typeentity entity) typeentity : baseentity { var typestoregister = typeof(datacontext).getproperties(). where(p => p.propertytype == typeof(dbset<typeentity>)); //this code explodes in face:-) //please let me know how fix var dbsetitem = typestoregister.first(); var methodadd = dbsetitem.gettype().getmethod("add"); methodadd.invoke(this, new typeentity[] { entity }); } } //insert<typeentity>(typeentity entity) service //method invoke dbset<t>.add() method.
this error get: object reference not set instance of object.
i fixed code. there 2 mistakes:
- instead of
var methodadd = dbsetitem.gettype().getmethod("add");
you should write: (because dbsetitem.gettype() return propertytype not type of field expected)
dbsetitem.getvalue(this).gettype().getmethod("add");
- and change row (because add method should invoked way: db.items.add(...) not db.add(...))
methodadd.invoke(this, new typeentity[] { entity> });
to one:
methodadd.invoke(dbsetitem.getvalue(this), new typeentity[] { entity> });
and did forget invoke savechanges method @ end of code?
public void insert<typeentity>(typeentity entity) typeentity: baseentity { var typestoregister = typeof(datacontext).getproperties(). where(p => p.propertytype == typeof(dbset<typeentity>)); var dbsetitem = typestoregister.first(); var methodadd = dbsetitem.getvalue(this).gettype().getmethod("add"); methodadd.invoke(dbsetitem.getvalue(this), new typeentity[] { entity }); savechanges(); }
Comments
Post a Comment