获取插入行的ID

osh*_*nen 1 c# sql-server asp.net asp.net-3.5 sql-server-2008

我试图使用sql输出子句从数据库中获取新插入记录的id,即

insert into table1(forename, surname) output inserted.id values(@forename, @surname)
Run Code Online (Sandbox Code Playgroud)

我试图像这样捕获id:

Int32 id = (int)command.ExecuteScalar;
Run Code Online (Sandbox Code Playgroud)

这给了我一条错误信息:

Compiler Error Message: CS0428: Cannot convert method group 'ExecuteScalar' to non-delegate type 'int'. Did you intend to invoke the method?
Run Code Online (Sandbox Code Playgroud)

不确定我做错了什么.

以下是现有代码的大量摘录:

using (connection = new SqlConnection(ConfigurationManager.AppSettings["connString"]))
{
    using (command = new SqlCommand("insert into table1(forename, surname) OUTPUT INSERTED.ID values(@forename, @surname)", connection))
    {
        command.Parameters.Add("@forename", SqlDbType.VarChar, 255).Value = forename;
        command.Parameters.Add("@surname", SqlDbType.VarChar, 255).Value = surname;

        command.Connection.Open();
        id = (int)command.ExecuteScalar;
    }
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*ant 5

试试id = (int) command.ExecuteScalar().你刚离开了parens.