在EF插入后,用EF执行命令来获取最新的ID [英] Struggling with EF's Execute Commands to get the newest ID after an insert

查看:571
本文介绍了在EF插入后,用EF执行命令来获取最新的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对DB(SQL Server 2008)直接发出一个Insert语句,在ASP.NET 4.5上使用EF6.1。我需要在交易帖子插入中获取最新的ID,但是我无法弄清楚代码。



这是我目前所拥有的:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆