我是使用 SQL Server 使用实体框架的新手,在将记录插入数据库时遇到问题。问题在于 3 个与主键和一个外键链接的表,过去我没有使用带外键的数据库。
我现在只是想将一些测试数据输入数据库,但我不断收到错误消息:
INSERT 语句与 FOREIGN KEY 冲突
谁能帮我开始插入我的数据库吗?这是我正在使用的代码:
private void button3_Click(object sender, EventArgs e)
{
TaxiDBEntities db = new TaxiDBEntities(); //connection to database
DriverStatus newDriverStatus = new DriverStatus(); // driver status object
/*populate the new driver object*/
//newDriverStatus.DriverID = Convert.ToInt32(driverComboBox.Text);
//newDriverStatus.Status = statusTextBox.Text;
//newDriverStatus.Area = areaTextBox.Text;
Driver driver = new Driver();
int driverIDInt = Convert.ToInt32(driverComboBox.Text);
//driver = db.Drivers.SingleOrDefault(p => p.DriverId == driverIDInt);
//if (driver == null)
//{
driver.DriverId = driverIDInt;
driver.Fname = "test";
driver.Lname = "test";
//}
db.DriverStatus.AddObject(newDriverStatus); // add driver object to entity model
DriverLog driverLog = new DriverLog();
driverLog.driverLogID = driverIDInt;
driverLog.DriverID = driverIDInt;
driverLog.date = DateTime.Now;
db.DriverLog.AddObject(driverLog);
DriverStatus driverStatus = new DriverStatus();
driverStatus.DriverID = driverIDInt;
driverStatus.Status = "1";
driverStatus.Area = "1";
db.DriverStatus.AddObject(driverStatus);
try
{
db.SaveChanges();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}