在父节点之前保存子节点,没有复制c#



我们有一个class parent

public class Parent {
int Id {get;set;}
Child child {get;set;}
}

和class child

public class Child {
int Id {get;set;}
string Info {get;set;}
}

创建一个child对象并保存为db

Child child = new Child();
dbContext.Child.Add(child);
dbContext.SaveChanges();

然后创建父对象并将创建的子对象分配给父对象(稍后使用)

Parent parent = new Parent();
parent.child=child;
dbContext.Parent.Add(parent);
dbContext.SaveChanges();

在db中保存父对象后的问题,我在db的子类中得到一个重复的子对象。请注意,我使用sql Server作为db.

我想把孩子的对象分配给父母,当我在db中保存父母时,父母不再保存孩子,请有任何解决方案吗?

试试这个

Parent parent = new Parent();
var existingChild = dbContext.Child.Find(child.id);
if (existingChild != null){
parent.child = existingChild;
}
dbContext.Parent.Add(parent);
dbContext.SaveChanges();

为了避免再次插入,如果它已经存在,您可以在将子对象附加到上下文后将dbContext设置为Unchanged。

在保存子对象后添加以下代码:

dbContext.Entry(child).State = EntityState.Unchanged;

我发现的唯一解决方案是只调用一次dbcontext的save方法(我只在保存父类时调用它),否则它将在数据库中保存两次。

最新更新