执行ExecuteSqlCommand后检索插入的ID?

时间:2017-02-21 14:07:53

标签: c# sql entity-framework

我想在执行此命令后检索插入的ID:

db.Database.ExecuteSqlCommand("INSERT INTO Table_Ressources (IdTypeRessource, IdSociete, IdTypeFormatIntitule_UR)Values (1,1,1);

我该怎么办?

3 个答案:

答案 0 :(得分:1)

您希望使用带有ExecuteScalar的OUTPUT来返回INSERTED(甚至更新)记录的ID。

INSERT INTO Table_Ressources (IdTypeRessource, IdSociete, IdTypeFormatIntitule_UR) 
OUTPUT INSERTED.Id
VALUES (1,1,1);

该语句将返回插入记录的ID。

一些参考:

https://msdn.microsoft.com/en-us/library/ms177564.aspx

How do I use an INSERT statement's OUTPUT clause to get the identity value?

答案 1 :(得分:0)

尝试在命令中添加SELECT SCOPE_IDENTITY(),然后查看ExecuteSqlCommand的返回值

答案 2 :(得分:0)

您需要使用" ExecuteScalar "而不是" ExecuteSqlCommand "。 ExecuteScalar按照此处的说明执行您所需的操作:

https://msdn.microsoft.com/pt-br/library/system.data.sqlclient.sqlcommand.executescalar(v=vs.110).aspx