Reputation: 5601
I am trying to insert a new entity using LINQ-to-SQL, and entity is associated with a User entity. The insert of the new entity is successful, but my existing User entity gets inserted as if it were a new User. The code looks something like the following:
var someEntity = new Entity();
someEntity.User = this.User;
dataContextInstance.SomeEntities.InsertOnSubmit(someEntity);
dataContextInstance.SubmitChanges();
Does anyone know why the user is being inserted as a brand new entity into the Users table? It would seem that the User.UserId would become the foreign key value in the UserId column of the row mapped to the someEntity that is being inserted.
Thanks for any help/suggestions/comments
Upvotes: 6
Views: 3347
Reputation: 9422
Since the User entity has been previously loaded by another DataContext (which should hopefully be disposed by now!), you have to attach it to the new (current) DataContext otherwise the DataContext will view it as a new Entity and not an existing one (which already exists in the DB).
Upvotes: 10
Reputation: 38003
Make sure you're using the same instance of DataContext for both tables. See my question here for (I think) a clearer explanation of the problem.
Upvotes: 0
Reputation: 176
Sorry, I don't get it? Do you want to update your existing user? What is someEntity for?
It makes sense, that LINQ tries to Insert a New user, because you tell it to do so. If you just want to change one of your users you need to select him out of SomeEntities, do the update and then call SubmitChanges (LINQ will recognize, that the original entity has been modified) - without .InsertOnSubmit.
Upvotes: -1