sql-serverentity-frameworkrawsql

Inserts using EF's RawSQL are not returning IDENTITY


Given:

In the original post I was attempting to call db.Database.ExecuteCommand, since then I changed that to what you see here. (Which works). Execute Command was always returning 0xfffff. SQLQuery returns the value of the last select statement or the rows inserted depending on how you code it up.

using (db=new MyEntites())
{
    var inserted = db.Database.SqlQuery<decimal>(query,parms}
}

Where last two lines in query are:

SET NOCOUNT OFF  
Select SCOPE_IDENTITY() AS newID  

Solution

  • Thanks to your suggestions, Step 1 put something like this in the query string as last select:

    Select SCOPE_IDENTITY() as TESTID;
    

    Then use this EF form of SQLQuery, the type of decimal is what is returned for the select example above.

    using (db=new MyEntites())
    {
       var identity = db.Database.SqlQuery<decimal>(query,parms}
    }