DEV Community

Cover image for System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException: Operation is not valid due to the current state of the object.
Sandeep Kumar
Sandeep Kumar

Posted on • Edited on

3 2

System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException: Operation is not valid due to the current state of the object.

You might have sometime faced the below exception while attempting to update an entity property:

System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException: Operation is not valid due to the current state of the object.

Reason:

After looking into the issue I found that this error occurs when an attempt is made to change a foreign key when the entity is already loaded.
In this case, I was trying to assign a value to the foreign key property, and an exception is thrown as foreign key fields and association properties don’t match, when changes are submitted.

In such a scenario there are two values, one in the foreign key field or the one on the other side of the relationship and it doesn’t know which value is correct, and as a result exception is thrown.

Solution:

To avoid the exception the best way to update the relationship is by changing the association property and not the foreign keys. And then it will automatically keep the foreign keys in sync when you assign the association property a value.

The foreign key field value is changed only when there is either no association property defined on the object or the association property was never assigned a value.

For Example we have Address object and Country as it's child object, with foreign column is CountryId:

Then if we do

dbContext.Address.CountryId = newCountryId;
Enter fullscreen mode Exit fullscreen mode

it'll raise exception, to avoid this update the relationship by changing the association property as:

dbContext.Address.Country = db.Country.Single(c => c.Id = newCountryId);
Enter fullscreen mode Exit fullscreen mode

Originally published at http://diary-techies.blogspot.com on
March 20, 2014.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay