在SaveChanges()上获取INSERT语句与FOREIGN KEY冲突

时间:2012-10-29 14:16:40

标签: c# sql-server-2008 entity-framework exception-handling foreign-keys

我不熟悉使用SQL Server的Entity Framework,我在将记录插入数据库时​​遇到问题。问题是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());
    }
}

3 个答案:

答案 0 :(得分:2)

driver对象实际插入到数据库中似乎缺失了。行后

driver.notes = "test";

你应该有像

这样的东西
db.Driver.AddObject(driver);

然后继续创建driverLogdriverStatus个对象。

答案 1 :(得分:1)

您需要先将驱动程序插入数据库,然后才能添加状态或日志。在填充驱动程序对象后,您要做的第一件事是添加状态

答案 2 :(得分:1)

1)您从文本框int driverIDInt = Convert.ToInt32(driverComboBox.Text)获取了ID。这不是最佳解决方案,请考虑将其设为IDENTITY列。

2)你的模型表明Drive-DriverLog是1-n但你的代码不允许超过1 Log:

driverLog.driverLogID = driverIDInt;
driverLog.DriverID = driverIDInt;

3)您正在向Db添加newDriverStatus,但没有设置密钥。

4)如果您打算将newDriverStatusdriver相关联,那么添加driverStatus也会产生冲突。

并且,与其他人已经注意到的一样,您忘记将driver添加到数据库中。

总之,将列定义为INDENTITY并让fx处理外键要容易得多。只需使用newDriverStatus.Driver = driver;driverLog.Driver = driver;

即可