Question

Suppose a regular Controller and an ApiController with their context's ProxyCreationEnabled and LazyLoadingEnabled are set to true and false respectively.

There is a way to update entities in EF setting it's state to EntityState.Modified.

_context.Entry(newEntity).State = EntityState.Modified;
_context.SaveChanges();

When the entity is loaded on the Controller everything works as expected. As for the ApiController having my navigation properties to null - because of disabling the proxies for that instance of the context.

What will happen if I change any property or set it's state to Modified and save the changes? What will entity framework do with those null navigation properties?

Was it helpful?

Solution

It depends whether you are using independent or foreign key associations.

For independent associations - these are associations that don't have the foreign key as a property in your model, but only the navigation property - nothing will happen with the navigation properties and foreign key values in the database if you set the state to Modified. They remain unchanged because the generated UPDATE statement won't include a change of the FK column value. It's by the way also the case if the navigation property is not null. Setting the entity state to Modified does not affect navigation properties, only scalar properties.

If you have foreign key associations - associations that have the foreign key as a property in your model - setting the state to Modified will mark the foreign key property as Modified because it is a scalar property. As a result the current FK property value will be written to the database and possibly change a relationship there, even if the navigation property is null.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top