Why does LINQ to SQL object association create a new (repeating) row when inserting a new record?

I am trying to insert a new object using LINQ-to-SQL, and the entity is associated with a User object. Inserting a new object was successful, but my existing user object is inserted as if it were a new user. The code looks something like this:

var someEntity = new Entity(); someEntity.User = this.User; dataContextInstance.SomeEntities.InsertOnSubmit(someEntity); dataContextInstance.SubmitChanges(); 

Does anyone know why the user is inserted as a new entity into the Users table? It would seem that User.UserId will become the value of the foreign key in the UserId column of the row associated with the someEntity insert.

Thanks for any help / suggestions / comments

+6
c # linq linq-to-sql
source share
3 answers

Since the user object was previously loaded by another DataContext (which, we hope, will now be deleted!), You must attach it to the new (current) DataContext, otherwise the DataContext will consider it as a new object, and not existing (which already exists in the database) .

+9
source share

Ensure that both tables use the same instance for the DataContext. See My question here for (I think) a clearer explanation of the problem.

0
source share

Sorry I do not understand? Do you want to update an existing user? What is someEntity for?

It makes sense that LINQ is trying to insert a new user because you are telling him that. If you just want to change one of your users, you need to select it from SomeEntities, perform the update, and then call SubmitChanges (LINQ will recognize that the original object has been changed) - without .InsertOnSubmit.

-one
source share

All Articles