C# 将ID转换为Int并保存到datatable

C# 将ID转换为Int并保存到datatable,c#,.net,sql-server,C#,.net,Sql Server,我一直在尝试将Customer表中的Customer\u ID添加到Customer\u Ship表中的Customer\u ID。我一直遇到客户ID无法正确转换为Int。有可能我并没有首先将新行添加到Customer\u Ship表中。非常感谢您的帮助,并提前表示感谢 if (customer_ID == "") { string SQL = "INSERT INTO Customer (Customer_Name) VALUES (@customer_Name); S

我一直在尝试将Customer表中的Customer\u ID添加到Customer\u Ship表中的Customer\u ID。我一直遇到客户ID无法正确转换为Int。有可能我并没有首先将新行添加到Customer\u Ship表中。非常感谢您的帮助,并提前表示感谢

    if (customer_ID == "")
    {
    string SQL = "INSERT INTO Customer (Customer_Name) VALUES (@customer_Name); SELECT Customer_ID FROM Customer WHERE Customer_ID = SCOPE_IDENTITY();";
    SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
    sqlCommand.Parameters.Add("@customer_Name", SqlDbType.VarChar, 100).Value = customer_Name;

    sqlConnection.Open();
    int customer_Id = (int)sqlCommand.ExecuteScalar();

    SQL = "INSERT INTO Customer_Ship (Customer_ID) VALUES (@customer_Id)";
    sqlCommand = new SqlCommand(SQL, sqlConnection);
    sqlCommand.Parameters.AddwithValue("@customer_Id", customer_Id);
    sqlCommand.ExecuteNonQuery();
    sqlConnection.Close();
    }
我看到两个错误:

您应该只返回SCOPE_IDENTITY-您可以将第一条INSERT语句简化为:

INSERT INTO Customer (Customer_Name) VALUES (@customer_Name); SELECT SCOPE_IDENTITY();";
这将从Customer表返回新插入的Customer_ID identity值-无需执行问题中的复杂选择

您需要从一开始就调用.ExecuteScalar-不要先调用.ExecuteNonQuery,然后再调用ExecuteScalar-这将执行语句两次-只需使用:

using(SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection))
{
     sqlCommand.Parameters.Add("@customer_Name", SqlDbType.VarChar, 100).Value = customer_Name;

     sqlConnection.Open();
     int customer_Id = (int)sqlCommand.ExecuteScalar();
     sqlConnection.Close();
}
这将把值插入Customer,并将新创建的Customer\u ID作为返回值返回到Customer\u ID,该ID已经是Int from.ExecuteScalar。然后可以使用此int值插入Customer_Ship表-无需转换-这已经是一个int值


不转换该值的可能原因是您试图转换空字符串customer\u ID:请参考代码的第1行,而不是从数据库中获取的customer\u ID。

不正确转换为Int是什么意思?您收到任何异常或错误消息吗?我收到一个未处理的类型异常,很抱歉没有具体说明。谢谢Marc_,我已经解决了这个问题,并在您的帮助下解决了我的问题。我已经修改了原来的代码帖子,以显示工作代码。我希望这也能帮助其他人。