title: Dynamically and performant call to add method on DbSet
body: <p>i would like to make a dynamic call on the Add method on DbSet that i don't know at the compilation.</p>
  
  <p>Actually, it's possible with simple reflection but the performance are awful. Here is the code we are using now :</p>
  
  <pre><code>Type contextType = (context as Object).GetType();
  var set = (contextType.GetProperty(entitySetName)).GetValue(context, null);
  Type typeSet = set.GetType();
  MethodInfo method = typeSet.GetMethod("Add");
  
  Object[] args = { entity };
  
  method.Invokke(set, args);
  </code></pre>
  
  <p>i've tried two others possibilities with different errors.</p>
  
  <p>The first other is to use delegate</p>
  
  <pre><code>public delegate void MyDel&lt;T&gt;(T t,object entity);
  
  Type contextType = (context as Object).GetType();
  var set = (contextType.GetProperty(entitySetName)).GetValue(context, null);
  Type typeSet = set.GetType();
  MethodInfo method = typeSet.GetMethod("Add");
  
  Type template = typeof(MyDel&lt;&gt;);
  Type specific = template.MakeGenericType(childClassType);
  Delegate test = Delegate.CreateDelegate(specific, method);
  </code></pre>
  
  <p>but on the last line, i get the following error : Error binding to target method</p>
  
  <p>And the third option is to use expression tree like this :</p>
  
  <pre><code>Type contextType = (context as Object).GetType();
  var set = (contextType.GetProperty(entitySetName)).GetValue(context, null);
  Type typeSet = set.GetType();
  MethodInfo method = typeSet.GetMethod("Add");
  
  
  ParameterExpression paramo = Expression.Parameter(typeSet, "param");
  ParameterExpression parami = Expression.Parameter(typeSet, "newvalue");
  Expression convertedParamo = Expression.Convert(paramo, typeof(Object));
  Expression convertedParami = Expression.Convert(parami, typeof(Object));
  
  MethodCallExpression methodCall = Expression.Call(convertedParamo, method, convertedParami);                    
  
  Expression valueExp = Expression.Lambda(methodCall, paramo, parami);
  Expression&lt;Action&lt;Object, Object&gt;&gt; dynamicExpression = (Expression&lt;Action&lt;Object, Object&gt;&gt;)valueExp;
  Action&lt;Object, Object&gt; dynamicAction = dynamicExpression.Compile();
  
  Object o = Activator.CreateInstance(otherType);
  dynamicAction(o, entity);
  </code></pre>
  
  <p>But in this case, at the line "Expression.Call(convertedParamo, method,..</p>
  
  <p>i got this error : </p>
  
  <blockquote>
    <p>Method 'DictionnaireONYX.Entites.ArticleSansFacturier
    Add(DictionnaireONYX.Entites.ArticleSansFacturier)' declared on type
    'System.Data.Entity.DbSet`1[DictionnaireONYX.Entites.ArticleSansFacturier]'
    cannot be called with instance of type 'System.Object'</p>
  </blockquote>
  
  <p>where ArticleSansFacturier is the DbSet. </p>
  
  <p>Who can help me ?</p>
  
  <p>Thanks in advance</p>