Entity framework Update fails when object is linked to a missing child
- by McKay
I’m having trouble updating an objects child when the object has a reference to a nonexising child record.
eg.
Tables Car and CarColor have a relationship. Car.CarColorId CarColor.CarColorId
If I load the car with its color record like so this
var result = from x in database.Car.Include("CarColor")
where x.CarId = 5
select x;
I'll get back the Car object and it’s Color object. Now suppose that some time ago a CarColor had been deleted but the Car record in question still contains the CarColorId value. So when I run the query the Color object is null because the CarColor record didn’t exist.
My problem here is that when I attach another Color object that does exist I get a Store update, insert error when saving.
Car.Color = newColor
Database.SaveChanges();
It’s like the context is trying to delete the nonexisting color.
How can I get around this?