【问题标题】:Retrieve the Inserted ID after executing ExecuteSqlCommand? [duplicate]执行 ExecuteSqlCommand 后检索插入的 ID? [复制]
【发布时间】:2017-02-21 14:07:53
【问题描述】:

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

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

请问我该怎么做?

【问题讨论】:

  • 这里的主键列是标识列,它不是这里指定的列吗?

标签: c# sql entity-framework


【解决方案1】:

您想将 OUTPUT 与 ExecuteScalar 一起使用以返回记录的 ID INSERTED(甚至更新)。

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?

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      您需要使用“ExecuteScalar”而不是“ExecuteSqlCommand”。 ExecuteScalar 可以满足您的需求,如下所述:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-08
        • 2011-07-27
        • 2011-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多