In my model I\'ve got a bunch of domain objects. Now I\'m having a problem when trying to update a User-object. The User has a foreignkey relation to the Role object. When I upd
To quote your comment:
However; if I set the navigation property user.Role to null it works just fine. But, is this the recommended way of working?
Yes, in this case it is.
You must keep in mind that you enter a new context with a detached object user
(including the reference to user.Role
). By setting the state to Modified
you attach the object user
together with the related user.Role
to this new context.
Because your are using a foreign key association - that means that the foreign key is represented by a property FkRoleId
in the model class - the relationship is described in two ways: By the navigation property user.Role
and by the scalar property user.FkRoleId
. If these are not consistent - i.e. user.Role.PkId != user.FkRoleId
- EF doesn't know which one describes the correct relationship and throws the exception you have.
If you set user.Role
to null
EF will consider the user.FkRoleId
alone as the property that describes the relationship between user and role and the ambiguity that was causing the exception is removed.