【问题标题】:How to insert auto generated ID into foreign key column [duplicate]如何将自动生成的ID插入外键列[重复]
【发布时间】:2019-10-03 02:46:12
【问题描述】:

所以我对 c# 和 SQL 还是很陌生。我有两个表(项目,Proptype)。这些是表格内的内容:

项目

  • ProjectId(主键、自动增量、整数)
  • PropTypeId(外键、自动增量、整数)
  • 项目名称
  • NumberOfUnits
  • 位置

属性类型

  • PropTypeId(主键、自动增量、整数)
  • 道具类型

我会将PropTypeId 放在一个组合框中,该组合框将显示Proptype 列的内容(已填充了值ResidentialIndustrial)。

这是程序的截图:Image of program with error.

这是我使用的代码:

SqlConnection sqlcon = new SqlConnection(dbconnectionstring);

try
{
    sqlcon.Open();

    SqlCommand createcommand = new SqlCommand("INSERT INTO [Project](ProjectName, NumberOfUnits, PropTypeId, Location)" +  
      "VALUES(@ProjectName, @NumberOfUnits, @PropTypeId, @Location)", sqlcon);

    createcommand.Parameters.AddWithValue("@ProjectName", prname.Text);
    createcommand.Parameters.AddWithValue("@NumberOfUnits", unitnum.Text);
    createcommand.Parameters.AddWithValue("@PropTypeId", prtype.Text);
    createcommand.Parameters.AddWithValue("@Location", locationtb.Text);

    createcommand.ExecuteNonQuery();

    MessageBox.Show("Saved");
    sqlcon.Close();
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

我正在使用 SQL Server,如果有帮助的话。

当我运行程序时,它显示错误

将 nvarchar 值“住宅”转换为数据类型 int 时转换失败。

我希望代码能够自动识别“住宅”的 ID 为“1”并将其放入项目表中。我想情况并非如此。希望有人可以帮助我。

提前致谢。

【问题讨论】:

  • 它是否自动递增似乎与您的问题无关:它是外部表中的自动递增键。它不会在您要插入的表中自动递增。你的问题的问题是你试图传递一个 C# string 一个 int 是预期的。
  • 我明白了。将其更改为 Proptype 列而不是 Proptype Id 会更容易吗?
  • 不,我很确定您在这里需要原型 id(作为整数)。请参阅链接的副本或 Metal 的答案。
  • 我试过金属的答案。它说“方法'ToInt32'没有重载需要0个参数”。接下来我将尝试找出如何从链接的副本中合并解决方案。

标签: c# sql-server


【解决方案1】:

我在想这个

 createcommand.Parameters.AddWithValue("@PropTypeId", prtype.Text);

应该是

 createcommand.Parameters.AddWithValue("@PropTypeId", Convert.ToInt32([prtTypeId.Text]));

【讨论】:

    猜你喜欢
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-04
    • 2019-12-10
    • 2012-09-04
    • 2015-07-24
    • 2017-10-10
    相关资源
    最近更新 更多