Entity framework Update fails when object is linked to a missing child

Posted by McKay on Stack Overflow See other posts from Stack Overflow or by McKay
Published on 2009-06-25T22:29:24Z Indexed on 2010/04/08 18:03 UTC
Read the original article Hit count: 159

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?

© Stack Overflow or respective owner

Related posts about entity-framework

Related posts about foreign-key-relationship