我的数据库中有两个表:category_table 和 subcategory_table。
类别表有以下列:id (int, PK), Category (varchar)
子类别表有以下列:id (int, PK), Category (int), Subcategory (varchar)
我正在尝试创建一个表单,用户可以在其中添加/删除类别和子类别。有两个组合框(用户可以在其中看到当前类别。只有从第一个组合框中选择了相应的类别才能看到子类别)。
我遇到的问题是将 category_table
(id) 主键关联到 subcategory_table
(类别);因此,无论在第一个组合框中选择什么类别,当添加子类别时,category_table
中该类别的 (id) 都会分配给 subcategory_table
中的 (Category) 列.
我知道可以使用外键;但是,我不知道在这种情况下该怎么做。
添加类别:
//ADD CATEGORY
private void addcat_Click(object sender, EventArgs e)
{
using (var sqlcmd = new SqlCommand("INSERT INTO category_table (Category) VALUES(@cat);", sqlconnection))
{
sqlcmd.Parameters.AddWithValue("@cat", this.cat_txtbx.Text);
sqlcmd.ExecuteNonQuery();
}
this.DialogResult = DialogResult.OK;
this.Close();
}
添加子类别:
//ADD SUBCATEGORY
private void addsubcat_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(combobox1.Text))
{
MessageBox.Show("You must select a category in which to add a subcategory.", "Invalid Operation: Data Missing", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
using (var sqlcmd = new SqlCommand("INSERT INTO subcategory_table (Subcategory) VALUES(@subcat);", sqlconnection))
{
sqlcmd.Parameters.AddWithValue("@subcat", this.subcat_txtbx.Text);
sqlcmd.ExecuteNonQuery();
}
}
this.DialogResult = DialogResult.OK;
this.Close();
}
最佳答案
使用添加子类别方法中的代码,添加创建外键关系所需的内容:
//ADD SUBCATEGORY
private void addsubcat_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(combobox1.Text))
{
MessageBox.Show("You must select a category in which to add a subcategory.", "Invalid Operation: Data Missing", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
using (var sqlcmd = new SqlCommand("INSERT INTO subcategory_table (Category, Subcategory) VALUES(@category, @subcat);", sqlconnection))
{
// Added this next line, and the corresponding parts in the INSERT statement above.
sqlcmd.Parameters.AddWithValue("@category", this.combobox1.SelectedValue);
sqlcmd.Parameters.AddWithValue("@subcat", this.subcat_txtbx.Text);
sqlcmd.ExecuteNonQuery();
}
}
this.DialogResult = DialogResult.OK;
this.Close();
}
-- 编辑更多信息--
我建议将 combobox1 重命名为有意义的名称,例如“类别”或对您的目的有意义的名称。
另外,我注意到没有强制的外键关系,因为你说添加了空值。你呈现你想要完成的事情的方式,我认为有类别和子类别,但没有更多级别。如果有更多层次,那么@mycargus 已经提供了一个很好的数据结构替代方案。如果只有这两个级别,看起来子类别需要有一个主要的“类别”。
我建议在数据库端强制执行外键关系,以防止空值和“category_table”中不存在的 ID
关于c# - 在数据库表之间形成关系 (C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29835554/