2012-01-20 45 views
1

我想從使用SQL輸出條款數據庫新插入記錄的ID,即獲得一個插入的行的ID

insert into table1(forename, surname) output inserted.id values(@forename, @surname) 

,我試圖捕捉到這樣的標識:

Int32 id = (int)command.ExecuteScalar; 

這是給我的錯誤信息:

Compiler Error Message: CS0428: Cannot convert method group 'ExecuteScalar' to non-delegate type 'int'. Did you intend to invoke the method? 

不知道我做錯了。

這裏是一個大的提取物中的現有代碼:

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; 
    } 
} 

回答

5

嘗試id = (int) command.ExecuteScalar()。你剛剛離開了父母。

3

ExecuteScalar是一種方法,所以你必須在它之後放置一個參數列表:ExecuteScalar()。

任何時候當您收到有關MethodGroups的錯誤時,這都可能是錯誤。