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. enter image description here

i fixed code. there 2 mistakes:

  1. 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");

  1. 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

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -