以下は、2 つの部分からなるコードのセクションです。お互いにほぼ同じ。どちらもテーブルに何かを挿入してから、Scope_identity を呼び出します。AddressType が挿入されていることを確認したところ、CityId が正しく表示されました。違いがわかりません。コードを調べましたが、間違いが見つかりません。誰かが余分な目になって、明らかな間違いに違いないことを指摘してくれることを願っています.
SqlCommand addressTypeCommand = new SqlCommand(
"INSERT INTO AddressType VALUES ('" + customerRow.AddressType + "');",
newCustConnection);
try
{
addressTypeCommand.ExecuteNonQuery();
}
catch (SqlException addressTypeException)
{
if (addressTypeException.ToString().StartsWith(
"Violation of UNIQUE KEY constraint"))
{
Console.WriteLine("Unique Key exception on 'AddressType'.");
}
}
SqlCommand selectAddressTypeID = new SqlCommand(
"select SCOPE_IDENTITY();", newCustConnection);
string addressTypeID = selectAddressTypeID.ExecuteScalar().ToString();
SqlCommand cityCommand = new SqlCommand(
"INSERT INTO City VALUES ('" + customerRow.City + "');",
newCustConnection);
try
{
cityCommand.ExecuteNonQuery();
}
catch (SqlException cityException)
{
if (cityException.ToString().StartsWith(
"Violation of UNIQUE KEY constraint"))
{
Console.WriteLine("Unique Key exception on 'City'.");
}
}
SqlCommand selectCityID = new SqlCommand(
"select SCOPE_IDENTITY();", newCustConnection);
string cityID = selectCityID.ExecuteScalar().ToString();