问题
I am issuing an Insert statement directly against the DB (SQL Server 2008), using EF6.1 on ASP.NET 4.5. I need to get the newest ID in the transaction post insert, however I cannot quite figure out the code.
This is what I have at present:
db.ExecuteStoreCommand("INSERT INTO Order ([SupplierId]) Values ({0})", SID);
Int32 intId = db.ExecuteStoreQuery<Int32>("SELECT SCOPE_IDENTITY()").First();
var myOrder = db.Order.First(r => r.Id == intId);
The above example is simplified. Is it possible combine the commands ie something like, or what?
Int32 intId = db.ExecuteStoreQuery<Int32>("INSERT INTO Order ([SupplierId]) Values ({0}); SELECT SCOPE_IDENTITY()",SID).First();
Thanks in advance.
回答1:
My suspicions were correct. This works:
Int32 intId = (Int32)db.ExecuteStoreQuery<Decimal>("INSERT INTO Order ([SupplierId]) Values ({0}); SELECT SCOPE_IDENTITY();", SID).First();
Hope this helps someone.
EDIT: As per Gert's answer, I have changed this from @@IDENTITY to use SCOPE_IDENTITY, more info also at More Information about Scope_Identity
来源:https://stackoverflow.com/questions/28153878/struggling-with-efs-execute-commands-to-get-the-newest-id-after-an-insert