c# - 无法将数据插入 SQL Server 中的外键
问题描述
ClassTable
:**
CREATE TABLE ClassTable
(
className varchar(255) NOT NULL PRIMARY KEY,
classFee int,
academicYear int
);
StudentTable
:
CREATE TABLE StudentTable
(
id int NOT NULL IDENTITY(1,1) PRIMARY KEY,
firstName varchar(255) NOT NULL,
lastName varchar(255),
fatherName varchar(255),
fatherNo varchar(255),
motherName varchar(255),
motherNo varchar(255),
dob date,
dor date,
gender varchar(255),
className varchar(255),
healthInsuranceNo varchar(255),
resAddress varchar(255),
photo Image,
CONSTRAINT FK_StudentTable
FOREIGN KEY (className) REFERENCES ClassTable(className)
);
C#代码:
cmd = new SqlCommand("INSERT INTO StudentTable (firstName, lastName, fatherName, fatherNo, motherName, motherNo, dob, dor, gender, className, healthInsuranceNo, resAddress, photo) VALUES (@firstName, @lastName, @fatherName, @fatherNo, @motherName, @motherNo, @dob, @dor, @gender, @className, @healthInsuranceNo, @resAddress, @photo)", con);
con.Open();
cmd.Parameters.AddWithValue("@firstName", txt_FirstName.Text);
cmd.Parameters.AddWithValue("@lastName", txt_LastName.Text);
cmd.Parameters.AddWithValue("@fatherName", txt_FatherName.Text);
cmd.Parameters.AddWithValue("@fatherNo", txt_FatherNo.Text);
cmd.Parameters.AddWithValue("@motherName", txt_MotherName.Text);
cmd.Parameters.AddWithValue("@motherNo", txt_MotherNo.Text);
cmd.Parameters.AddWithValue("@dob", dateTimePickerDOB.Text);
cmd.Parameters.AddWithValue("@dor", dateTimePickerDOR.Text);
cmd.Parameters.AddWithValue("@gender", cmb_Gender.Text);
cmd.Parameters.AddWithValue("@className", cmb_Class.Text);
cmd.Parameters.AddWithValue("@healthInsuranceNo", txt_HealthInsurance.Text);
cmd.Parameters.AddWithValue("@resAddress", txt_Address.Text);
MemoryStream ms = new MemoryStream();
img_Box.Image.Save(ms, img_Box.Image.RawFormat);
cmd.Parameters.AddWithValue("@photo", ms.ToArray());
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Accountant successfully registered.");
当我手动将查询写入 SQL Server 时,它允许我将数据插入外键列 ( className
),但是当我尝试从 C# Winforms 应用程序插入时,我收到此错误:
INSERT 语句与 FOREIGN KEY 约束“FK_StudentTable”冲突。冲突发生在数据库“SchoolDatabase”、表“dbo.ClassTable”、列“className”中。
我使用此查询在数据库中手动输入一条记录,它起作用了:
INSERT INTO StudentTable (firstName, className)
VALUES ('name here', 'class one');
解决方案
推荐阅读
- c# - 集合中的“_version”有什么用?
- sql-server - 如何使用 AJAX 从 MVC 中的数据库中检索“大”文件
- c# - 获取电报频道消息的消息ID
- javascript - 缺少 1 天的天数差异(javascript)?
- c# - AmazonCognitoIdentityProviderException:用户无权对资源执行 cognito-idp:DescribeUserPool
- c# - 光子螺栓 | 创建后将房间设为私有
- rest - 跨多个组织的基于网络的长期应用程序在 REST 中意味着什么?
- python-3.x - 通过映射 df2 中的同一列并在 pandas 中应用特定计算,在 df1 中创建新列
- sql - 在sql中用NULL替换列中的字符串
- flutter - 如何防止广告在 Flutter_native_admob 中的 ListView/GridView 上重新加载?