Question: How do you solve Entity Framework Error: "InvalidOperationExecption: The property 'EntityName.Id' is part of a key and so cannot be modified or marked as modified. To change the principal of an existing entity with an identifying foreign key, first delete the dependent and invoke "SaveChanges", and then associate the dependent with a new principal."
Answer: Take a look into the function that is utilizing Entity Framework and make sure that you are calling functions like:
[Note]: The Order of which the Entities are removed from the Entity Framework ChangeTracker is important. We have to understand that when Entity Framework Tracks Entities it tries to understand the relationships of the Entities, however when it finds a Key in another Entity that seem similar in naming Conversions it trys to make an educated guess whether to mark that as a Foraign Key or not.
In some instances it marks Keys related to other Keys found in other Entities as Foreign Keys, hence the error occurs. Do not remove Entities in Order that would trigger that error. Take an example below:
In this case, MyEntity 2 might have a dependency on MyEntity1 resulting in an error, even when you did not explicitly make a dependency in relationship from the Database, the error will still be thrown.
[Solution 2]: If the above solution does not help you solve the error then try to Save Changes to the Database for every Deletion Operation (This is calling the Database N Times which is not recommended), always come up with ways to optimize your queries and make sure you are calling the Database when need to.
Good Luck :) and let me know by leaving a comment below if this helped you.