在EF插入后,用EF执行命令来获取最新的ID [英] Struggling with EF's Execute Commands to get the newest ID after an insert
问题描述
这是我目前所拥有的:
db.ExecuteStoreCommand(INSERT INTO Order([SupplierId])Values({0}),SID);
Int32 intId = db.ExecuteStoreQuery< Int32>(SELECT SCOPE_IDENTITY())。
var myOrder = db.Order.First(r => r.Id == intId);
上面的例子是简化的。是否可以组合命令,例如,或什么?
Int32 intId = db.ExecuteStoreQuery< Int32>(INSERT INTO订单([SupplierId])值({0}); SELECT SCOPE_IDENTITY(),SID).First();
提前感谢
我的怀疑是正确的。这样做:
Int32 intId =(Int32)db.ExecuteStoreQuery< Decimal>(INSERT INTO Order([SupplierId] ({0}); SELECT SCOPE_IDENTITY();,SID).First();
希望这有助于某人。
编辑:根据Gert的回答,我已将其从@@ IDENTITY更改为使用SCOPE_IDENTITY,更多信息也可在有关Scope_Identity的更多信息
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.
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
这篇关于在EF插入后,用EF执行命令来获取最新的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!