Linq Update FK – Operation is not valid due to the current state of the object

sql serverTo update the entity in question you need to get a new entity for it from the context rather than setting it directly.

Wrong Way

[sourcecode lang=”c”]
OrderRecord.customerId = 105;
[/sourcecode]
Throws an error!
“Operation is not valid due to the current state of the object”

Solution

[sourcecode lang=”c”]
OrderRecord.tblCustomer = db.tblCustomers.Single(t => t.customerID == 105);
[/sourcecode]
Returns no error!

Leave a Reply

Your email address will not be published.