简体   繁体   中英

C# , SQL FOREIGN KEY

I am trying to insert data into the table 'table' , but I am stocked with the error of foreign key , 'building_id' from the building table , how do I get through it?

Error prompt:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_user_user".
The conflict occurred in database "C:\\USERS\\USER\\DOWNLOADS\\VIUSAL\\VIUSAL\\ENERGYVIUSAL\\ENERGYVIUSAL\\DATABASE1.MDF", table "dbo.building", column 'building_id'. The statement has been terminated.

This is the code:

DataRow drowEmployee = dsetEnergyViusal.Tables["Table"].NewRow();
drowEmployee["Name"] = txtName.Text;
drowEmployee["ContactID"] = Convert.ToInt32(txtContactId.Text);
drowEmployee["Company"] = txtCompanyId.Text;
drowEmployee["Building_id"] = txtBuildingID.Text;
drowEmployee["Telephone"] = txtContactNumber.Text;
drowEmployee["Email"] = txtEmail.Text;
drowEmployee["Password"] = txtPassword.Text;

if (radClient.Checked)
   drowEmployee["Client"] = radClient.Checked;
else if (radNews.Checked)
   drowEmployee["News"] = radNews.Checked;

drowEmployee["Telephone"] = txtContactNumber.Text;

dsetEnergyViusal.Tables["Table"].Rows.Add(drowEmployee);

sqldaEnergyViusal.Update(dsetEnergyViusal, "Table");

MessageBox.Show("Record has been successfully added.", "EnergyViusal", MessageBoxButtons.OK, MessageBoxIcon.Information);
User_register_Load(null, null);

您可能在文本框中输入并在插入查询中发送的建筑物ID在建筑物表中不存在。

May be you will be added Building_Id as a foreign key in the currently inserting table. to avoid that you have to first insert into Building table and that inserted id has to be used in this insertion ie you have to use a valid building_id in the insertion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM