Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Because you're using dynamic as the argument to <code>CreateCommand()</code>, the <code>cmd</code> variable is also dynamic, which means its type is resolved at runtime to be <code>SqlCommand</code>. By contrast, the <code>conn</code> variable is not dynamic and is compiled to be of type <code>DbConnection</code>.</p> <p>Basically, <code>SqlCommand.Connection</code> is of type <code>SqlConnection</code>, so the <code>conn</code> variable, which is of type <code>DbConnection</code>, is an invalid value to set <code>Connection</code> to. You can fix this by either casting <code>conn</code> to an <code>SqlConnection</code>, or making the <code>conn</code> variable <code>dynamic</code>.</p> <p>The reason it worked fine before was because <code>cmd</code> was actually a <code>DbCommand</code> variable (even so it pointed to the same object), and the <code>DbCommand.Connection</code> property is of type <code>DbConnection</code>. i.e. the <code>SqlCommand</code> class has a <code>new</code> definition of the <code>Connection</code> property.</p> <p><strong>Source issues annotated:</strong></p> <pre><code> public static dynamic DynamicWeirdness() { dynamic ex = new ExpandoObject(); ex.TableName = "Products"; using (var conn = OpenConnection()) { //'conn' is statically typed to 'DBConnection' var cmd = CreateCommand(ex); //because 'ex' is dynamic 'cmd' is dynamic cmd.Connection = conn; /* 'cmd.Connection = conn' is bound at runtime and the runtime signature of Connection takes a SqlConnection value. You can't assign a statically defined DBConnection to a SqlConnection without cast. */ } Console.WriteLine("It will never get here!"); Console.Read(); return null; } </code></pre> <p><strong>Options for fixing source (pick only 1):</strong></p> <ol> <li><p>Cast to statically declare <code>conn</code> as a SqlConnection: <code>using (var conn = (SqlConnection) OpenConnection())</code></p></li> <li><p>Use runtime type of <code>conn</code>: <code>using (dynamic conn = OpenConnection())</code></p></li> <li><p>Don't dynamic bind CreateCommand: <code>var cmd = CreateCommand((object)ex);</code></p></li> <li><p>Statically define <code>cmd</code>: <code>DBCommand cmd = CreateCommand(ex);</code></p></li> </ol>
 

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