我想執行此命令後檢索插入ID:執行ExecuteSqlCommand後檢索插入的ID?
db.Database.ExecuteSqlCommand("INSERT INTO Table_Ressources (IdTypeRessource, IdSociete, IdTypeFormatIntitule_UR)Values (1,1,1);
我應該如何做到這一點嗎?
我想執行此命令後檢索插入ID:執行ExecuteSqlCommand後檢索插入的ID?
db.Database.ExecuteSqlCommand("INSERT INTO Table_Ressources (IdTypeRessource, IdSociete, IdTypeFormatIntitule_UR)Values (1,1,1);
我應該如何做到這一點嗎?
嘗試增加SELECT SCOPE_IDENTITY()
的命令,看看ExecuteSqlCommand
的返回值,您需要使用「的ExecuteScalar」,而不是「ExecuteSqlCommand」。 的的ExecuteScalar做你所需要的,如下解釋:
您想要使用的ExecuteScalar輸出到返回插入記錄(甚至更新)的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?
這裏的主鍵科拉姆是標識列,它是沒有問題這裏指定的列? –