为什么LINQ to SQL的实体关联创建一个新的(副本)行插入新记录什么时候?什么时候、副本、创建一个、实体

2023-09-04 22:39:36 作者:尽揽少女心

我想插入使用LINQ到SQL一个新的实体,以及实体与用户实体相关联。新实体的插入是成功的,但我现有的用户实体被插入,就好像它是一个新的用户。在code看起来像下面这样:

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();

有谁知道为什么用户要插入一个全新的实体到用户表?这似乎是在User.UserId将成为映射到被插入的所述someEntity的行的用户ID列中的外键值

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

推荐答案

由于用户的实体已被其他的DataContext pviously加载$ P $(这应该有希望被处理现在!),你必须把它附加到新(电流)的DataContext否则在DataContext将其视为一个新的实体,而不是现有的(其已经存在于DB)中。

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