Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is LINQ to SQL entity association creating a new (duplicate) row when inserting a new record?

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

like image 509
mkelley33 Avatar asked Apr 24 '09 10:04

mkelley33


1 Answers

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).

like image 88
RobS Avatar answered Oct 18 '22 01:10

RobS