Entity Framework: Setting EntityReference EntityKey causes exception on save

Posted by NYSystemsAnalyst on Stack Overflow See other posts from Stack Overflow or by NYSystemsAnalyst
Published on 2010-04-23T14:21:29Z Indexed on 2010/04/23 14:23 UTC
Read the original article Hit count: 244

Filed under:
|
|

I have a table with a ModifiedUserID field that is a foreign key to a User table. In entity framework, I'm loading the first table, but not the users table. I have the user ID of the current user, and would like to set the ModifiedUserID to that value for all entities that have been modified prior to saving.

Before calling SaveChanges(), I use the ObjectStateManager to get all modified entities. Since I do not have the user object, but I do have the user ID, I set the EntityReference.EntityKey property as follows:

entity.UserReference.EntityKey = New EntityKey("MyContainer.User", "UserID", DatabaseUserID)

This works fine, but when I execute SaveChanges(), I receive the following error:

A relationship is being added or deleted from an AssociationSet 'FK_Table1_User'. With cardinality constraints, a corresponding 'Table1' must also be added or deleted.

Now, I see that setting the EntityReference.EntityKey creates a new AssociationSet entry, but how to I prevent this error?

© Stack Overflow or respective owner

Related posts about entity-framework

Related posts about .net-3.5