title: What is happening when dbcontext.Database.ExecuteSqlCommand is called?
body: <p>I am using Entity Framework Code First from database. I'm trying to run an existing unmapped stored procedure, using dbcontext.Database.ExecuteSqlCommand, dynamically creating the query and parameter array based on values passed in from the JSON (there are many optional parameters). I am not expecting a return value. </p>
  
  <p>When I test from my service, I get SqlExceptions being thrown from within the stored proc:</p>
  
  <blockquote>
    <p>Cannot insert the value NULL into column 'yyyyww', table 'dbname.dbo.table'; column does not allow nulls.</p>
  </blockquote>
  
  <p>But when I run the same query using the same values from SSMS '12, there are no errors. The table does actually allow nulls for that column.</p>
  
  <pre><code>exec [dbname].[dbo].[storedproc] @yyyymm = 201409, @s_id = 75
  </code></pre>
  
  <p>Passing an optional string parameter causes an exception about converting nvarchar to int, which doesn't happen in the stored proc. I've tried a few different ways to set up the call, but they all throw the same exceptions.</p>
  
  <p>version 1:</p>
  
  <pre><code>string query1 = "exec [dbname].[dbo].[storedproc] @yyyymm, @s_id";
  
  List&lt;SqlParameter&gt; parms1 = new List&lt;SqlParameter&gt;();
  parms1.Add(new SqlParameter("@yyyymm", obj.yyyymm));
  parms1.Add(new SqlParameter("@s_id", obj.s_Id));
  
  db.Database.ExecuteSqlCommand(query, parms1.ToArray());
  </code></pre>
  
  <p>version 2:</p>
  
  <pre><code>string query2 = "exec [dbname].[dbo].[storedproc] @yyyymm, @s_id";
  
  var month = new SqlParameter("yyyymm", SqlDbType.Int);
  month.Value = obj.yyyymm;
  var s_id = new SqlParameter("s_id", SqlDbType.Int);
  s_id.Value = obj.s_Id;
  
  List&lt;SqlParameter&gt; parms2 = new List&lt;SqlParameter&gt;();
  parms2.Add(month);
  parms2.Add(s_id);
  
  db.Database.ExecuteSqlCommand(query, parms2.ToArray());
  </code></pre>
  
  <p>version 3:</p>
  
  <pre><code>string query3 = "exec [dbname].[dbo].[storedproc] @yyyymm = {0}, @s_id = {1}";
  db.Database.ExecuteSqlCommand(query3, obj.yyyymm, obj.s_Id);
  </code></pre>
  
  <p>Any thoughts on what is happening - why the values are being treated differently? Is there a better way to do this?</p>