Struggling with EF's Execute Commands to get the newest ID after an insert

社会主义新天地 提交于 2020-01-17 08:09:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!