Question

I have a Person table that has a nullable AddressId in it which is foreign keyed to an Address table. So zero..one to many.

Using EF and ObjectContext I can call person.Address to access the Address object for a person. Neat!

Look at this fairly simple code then I'll tell you my issue:

var _db = new DataContext();
Person person = _db.getThatOneGuy();

//some changes are done to the person object
person.FirstName = "Harry";

//If there's no address I want to make one
if(person.Address == null)
person.Address = new Address();

person.Address.StreetOne = "blah";
person.Address.StreetTwo = "blah";

//I decide I don't actually want this new address
person.Address = null;

_db.SaveChanges();

The call to SaveChanges() will still generate an sql UPDATE (firstname = 'Harry') which is great BUT it also generates an sql INSERT statement trying to add that new address (blah, blah). (I know because I checked the generated SQL in sql profiler) It errors because I have fields like StateId that are not nullable, but I don't want it to even try to add that address (my attempt to stop it was by making it null) Help me please.

Note: I have before been successful with collections (many to many relationships) where I could do person.Addresses.Add(addressObj) then person.Addresses.Remove(addressObj) and the ObjectContext knows not to do an insert.... just not sure how to handle this 0..1 to many address situation.

Thanks.

Was it helpful?

Solution

The problem is that setting Address property to null does not remove Address instance from the context. It only informs context that there is no relation between Person instance and Address instance. You still have to remove Address instance from the context. Try this:

_db.Detach(person.Address);
_db.SaveChanges();

or:

var address = person.Address; 
person.Address = null;
_db.Detach(address);
_db.SaveChanges();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top