いくつかの回答を閲覧しましたが、うまく機能していないようです。
プログラムの別の部分で使用できるように、テーブルのIDフィールドを返す必要があります。
Convert.ToInt32(sqlComm.ExecuteScalar());
しかし、運がなく、同じです
Convert.ToInt32(sqlComm.Parameters["ID"].Value);
そして、レコードがテーブルに挿入されたとしても、両方とも0を返します。
以下のコードをダンプします、誰かが私が間違っていることを見ることができますか?
using (SqlConnection sqlConnect = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
using (SqlCommand sqlComm = new SqlCommand("up_Insert_Address", sqlConnect))
{
sqlComm.CommandType = CommandType.StoredProcedure;
sqlComm.Parameters.Add("@AddressID", SqlDbType.BigInt).Direction = ParameterDirection.Output;
sqlComm.Parameters.Add("@AddressLineOne", SqlDbType.NVarChar, 40).Value = address.AddressLineOne;
try
{
sqlComm.Connection.Open();
return Convert.ToInt32(sqlComm.ExecuteScalar());
}
catch (SqlException)
{
}
finally
{
sqlComm.Connection.Close();
}
}
}
およびストアドプロシージャ:
@AddressID Bigint OUTPUT,
@AddressLineOne NVarChar(40)
AS
BEGIN
BEGIN TRY
INSERT INTO Address
(
AddressLineOne
)
VALUES
(
@AddressLineOne
)
SET @AddressID = SCOPE_IDENTITY();
END TRY
BEGIN CATCH
DECLARE @Err nvarchar(500)
SET @Err = ERROR_MESSAGE()
RAISERROR(@Err, 16, 1)
END CATCH
END