I am new to working with the Entity Framework with SQL Server and I am having trouble inserting a record into my database. The problem is with 3 tables that are linked with primary keys and a foreign key and in the past I have not used databases with foreign keys.
I am just trying to get some test data into the database for now but I keep getting the error:
INSERT statement conflicted with the FOREIGN KEY
Can anyone help me get started with inserting into my database please? Here is the code I am using:
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());
}
}
Actual insert of the
driverobject into the database seems to be missing. After the lineyou should have something like
And then go on with creation of
driverLoganddriverStatusobjects.