为什么LINQ to SQL的实体关联创建一个新的(副本)行插入新记录什么时候? [英] Why is LINQ to SQL entity association creating a new (duplicate) row when inserting a new record?

查看:140
本文介绍了为什么LINQ to SQL的实体关联创建一个新的(副本)行插入新记录什么时候?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想插入使用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).

这篇关于为什么LINQ to SQL的实体关联创建一个新的(副本)行插入新记录什么时候?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆