C# 实体框架-在insert内部调用SaveChanges时复制相关实体

C# 实体框架-在insert内部调用SaveChanges时复制相关实体,c#,entity-framework,wcf-ria-services,C#,Entity Framework,Wcf Ria Services,我正在创建一个新的父实体,在客户端有一个新的子实体。这是一对多的关系 //Client has created a new Parent with a new Child attached //e.g. Parent.Child = new Child(); //This is submitted to the server, and ends up here: public void InsertParent(Parent parent) { ObjectContext.Paren

我正在创建一个新的父实体,在客户端有一个新的子实体。这是一对多的关系

//Client has created a new Parent with a new Child attached 
//e.g. Parent.Child = new Child();
//This is submitted to the server, and ends up here:
public void InsertParent(Parent parent)
{ 
    ObjectContext.Parents.AddObject(parent); //No Parent.ID yet
    ObjectContext.SaveChanges(); //Now I have a Parent.ID

    //Do some stuff with the Parent.ID here. (Nothing is changed with the Parent or Child, just using Parent.ID)
}
我的问题是,在所有这些之后,数据库中有两个子实体。我猜EF已经为排队的子实体创建了一个insert,当我调用SaveChanges时,它会为同一子实体创建另一个insert

我之所以在这里保存更改,是因为我希望在创建父对象后对Parent.ID执行一些操作,但我需要在父对象获得ID之前对其进行持久化(主键由DB创建)。当我取出所有额外代码(从SaveChanges开始)时,一切都按预期工作。

  • 在此方法中放置断点以确认父级上只有一个子级
  • 在SaveChanges()之后立即返回以确认您的其他“东西”没有进行任何其他更改
  • 确保ObjectContext被正确实例化和处理。为什么这个方法没有实例化上下文-它来自哪里
很难说这里发生了什么,除非您进行更多的调试并确定问题的确切位置


您的操作应该接受带有子对象的父对象,只需实例化上下文并插入。如果你能确认它只是这样做,那么你很可能会发现你的问题。

我知道这篇文章很老了,但我遇到了同样的问题,还没有找到解决问题的好方法。我正在使用带绑定的WPF。我正在尝试插入一条与多个子表关联的历史记录。最后,我要做的是确保未插入子项:

Parent.ChildID = Parent.Child.ChildID;
Parent.Child = null;
这似乎是一个完全的黑客,但它的工作