Note that there are some explanatory texts on larger screens.

plurals
  1. POExecuting Method Against DataContext Returning Inserted ID
    text
    copied!<p>Is there any way to use <code>DataContext</code> to execute some explicit SQL and return the auto-increment primary key value of the inserted row <em>without</em> using <code>ExecuteMethodCall</code>? All I want to do is insert some data into a table and get back the newly created primary key but without using LINQ (I use explicit SQL in my queries, just using LINQ to model the data).</p> <p>Cheers</p> <p><strong>EDIT</strong>: Basically, I want to do this:</p> <pre><code>public int CreateSomething(Something somethingToCreate) { string query = "MyFunkyQuery"; this.ExecuteCommand(query); // return back the ID of the inserted value here! } </code></pre> <p><strong>SOLUTION</strong></p> <p>This one took a while. You have to pass a reference for the OUTPUT parameter in your sproc in your parameter list of the calling function like so:</p> <pre><code>[Parameter(Name = "InsertedContractID", DbType = "Int")] ref System.Nullable&lt;int&gt; insertedContractID </code></pre> <p>Then you have to do</p> <pre><code>insertedContractID = ((System.Nullable&lt;int&gt;)(result.GetParameterValue(16))); </code></pre> <p>once you've called it. Then you can use this outside of it:</p> <pre><code>public int? CreateContract(Contract contractToCreate) { System.Nullable&lt;int&gt; insertedContractID = null; ref insertedContractID); return insertedContractID; } </code></pre> <p>Take heavy note of <code>GetParameterValue(16)</code>. It's indexed to whichever parameter it is in your parameter list (this isn't the full code, by the way).</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