title: Invoking DbSet<Type>.Add() method using reflections, in a child class of DbContext
body: <p>I've got a DbContext child class that talks to the Database through entity framework. I'm using MVC C#.</p>
  
  <p>I've got n DbSets related to my tables. I want to invoke the Add method for any DbSet.Add(entityObject), in this case <strong>UserAccounts.Add(entityUserAccount)</strong> using reflections or dynamic variable.</p>
  
  <p>I'm doing this because I need to inject DbContect by dependency injection in my controllers.</p>
  
  <pre><code>public class DataContext: DbContext
  {
       public DbSet&lt;UserAccount&gt; UserAccounts { get; set; }
  
       public void Insert&lt;TypeEntity&gt;(TypeEntity entity) where TypeEntity : BaseEntity
       {
          var typesToRegister = typeof(DataContext).GetProperties().
                       Where(p =&gt; p.PropertyType == typeof(DbSet&lt;TypeEntity&gt;));
  
          //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&lt;TypeEntity&gt;(TypeEntity entity) is my service 
  //method to invoke the DbSet&lt;T&gt;.Add() method.
  </code></pre>
  
  <p>This is the error I get: Object reference not set to an instance of an object.
  <img src="https://i.stack.imgur.com/dzOMQ.jpg" alt="enter image description here"></p>