Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF6: Modifying an entity property with a foreign key relation - Do I need to change the Id or the related object or both?

I am modifiying the foreign key property on an entity in code, by modifiying the Id only:

ElementData.ServiceLevelId = parameter.ServiceLevelId;

I have found, after persisting, that this only works as expected, when the corresponding navigation property ServiceLevel was null by accident. If it still holds the "old" object, the change will not hit the database.

This means, I need to do

ElementData.ServiceLevelId = parameter.ServiceLevelId;
ElementData.ServiceLevel = null; //Force the update to the Database

Does that mean, that changing the object is "stronger" than changing the id only? Should I always set the related object to null in such situations?

Update (per Tim Copenhaver's comment): The entity in question is a copy (with the mentioned modification) of an existing one. It uses Automapper for copying, and maps everything except the primary key and one unrelated property. Automapper creates a shallow copy AFAIK. Thus, the situation for the copy will be that the updated Id and the untouched object reference will not match at the moment of adding it to the context. I guess, that EF then decides that the "object reference is stronger".

like image 276
Marcel Avatar asked Oct 30 '22 11:10

Marcel


1 Answers

Changing either property will work as long as your data mapping is correct. EF is smart enough to see which of the properties has changed and ignore the other one. You have to be careful, though - if ElementData.ServiceLevel.Id does not equal ElementData.ServiceLevelId, you will get some obscure errors.

If you're having trouble with it not saving, your mapping layer is probably not correct. We can help troubleshoot if you can post the mapping for your ElementData class and some more code around how you're doing the save.

like image 84
Tim Copenhaver Avatar answered Nov 09 '22 11:11

Tim Copenhaver