I found the problem: the FK relationship between two of the tables had an issue.
How do you insert a complex object into the database?
-
11-07-2023 - |
Question
Let's say we have these three tables:
--Car--
ID
1
2
--Event--
ID CarID EventTypeID DateTimeAdded
1 1 1 2014-04-28 12:00:00
--EventType--
ID Name
1 "Entry Created"
2 "Entry added to sales chart"
3 "Entry removed from sales chart"
Using Entity Framework (EF 5 in my case), how would one add a Car object to the database? I have tried a number of different ways to accomplish this, including the code below, but nothing has worked yet.
Car newCar = new Car(){ }
Event newEvent = new Event(){
CarID = newCar.ID,
EventTypeID = 2,
DateTimeAdded = Datetime.Now;
}
newCar.Event.Add(newEvent);
context.Car.Add(newCar);
context.SaveChanges();
Any assistance would be greatly appreciated.
EDIT: The exception comes up in a try catch after context.SaveChanges() occurs. Here is the innerexception from the exception:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Event_EventType". The conflict occurred in database "CarSystem", table "dbo.EventType", column 'ID'
Note: there is a relationship between all three of these tables, including Event and EventType. Could this be causing the issue? If so, I've got no idea how to fix it.
La solution 2
Autres conseils
You may want to change the sequence of operations as follows:
context.Car.Add(newCar);
newCar.Event.Add(newEvent);
context.SaveChanges();
That way the INSERT call for the Car row (parent) will be issued before the INSERT call for the Event row (child), avoiding the foreign key error.