Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your cast is wrong.</p> <p>You can't cast to <code>(DbSet&lt;T&gt;)</code> because that's not a concrete type unless <code>T</code> is defined inside a generic method or generic type.</p> <p>You have a couple of possibilities.</p> <p>If DbSet has a base class (e.g. <code>DbSet_BaseClass</code> in my code below) from which you can still implement your <code>Clear()</code> method - then change it's signature from:</p> <pre><code>public static void Clear&lt;T&gt;(this DbSet&lt;T&gt;) </code></pre> <p>to:</p> <pre><code>public static void Clear(this DbSet_BaseClass) </code></pre> <p>Then you can change your cast in the <code>.ForEach</code> to <code>((DbSet_BaseClass)pi.GetValue...</code></p> <p>If you can't do that, you could reflect-invoke the <code>Clear</code> extension method by building a specific generic version of it for the <code>T</code> of the <code>DbSet&lt;T&gt;</code>:</p> <pre><code>MethodInfo myClearMethod = typeof(container_type).GetMethod( "Clear", BindingFlags.Public | BindingFlags.Static); </code></pre> <p>Then, given a property info and context instance:</p> <pre><code>Type propType = pi.PropertyType; Type typeofT = propType.GetGenericArguments[0]; MethodInfo toInvoke = myClearMethod.MakeGenericMethod(typeofT); //now invoke it toInvoke.Invoke(null, new[] { pi.GetValue(currentContext, null) }); </code></pre> <p>There are lots of optimisations you can put on top of this, caching delegates etc etc, but this will work.</p> <h2>Update</h2> <p>Or see @Daniel Hilgarth's answer for a <em>cool</em> way to dynamically dispatch the call to the extension method without having to do any of the above (dynamic dispatch effectively does something like the above, but for you with all the caching on top). If it were me - I'd be using that.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload