下面是一段包含两部分的代码。几乎一模一样。他们都在表中插入一些东西,然后调用 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();