Entity framework 在EF 5中为新对象使用循环外键引用的更好方法

Entity framework 在EF 5中为新对象使用循环外键引用的更好方法,entity-framework,entity-framework-5,dbcontext,circular-reference,Entity Framework,Entity Framework 5,Dbcontext,Circular Reference,我在一个web项目中首先使用EF5.0和DB 对于我们的服务层,我们使用Agatha和AutoMapper,因此所有数据都作为POCO对象到达服务层 我的数据结构如下所示: public class FirstClass { public int Id { get; set; } public int? SelectedSecondClassId { get; set; } public SecondClass SelectedSecondClass { get; se

我在一个web项目中首先使用EF5.0和DB

对于我们的服务层,我们使用Agatha和AutoMapper,因此所有数据都作为POCO对象到达服务层

我的数据结构如下所示:

public class FirstClass
{
    public int Id { get; set; }

    public int? SelectedSecondClassId { get; set; }
    public SecondClass SelectedSecondClass { get; set; }

    public ICollection<SecondClass> MySecondClasses { get; set; } 

    //other properties go here
}

public class SecondClass
{
    public int Id { get; set; }

    public int ParentSecondClassId { get; set }
    public SecondClass ParentSecondClass { get; set; }

    //other properties go here
}
公共类第一类
{
公共int Id{get;set;}
public int?SelectedSecondClassId{get;set;}
public SecondClass SelectedSecondClass{get;set;}
公共ICollection mysecondclass{get;set;}
//其他财产在这里
}
公务舱二等舱
{
公共int Id{get;set;}
public int ParentSecondClassId{get;set}
公共第二类ParentSecondClass{get;set;}
//其他财产在这里
}
现在,假设我尝试更新一个第一类对象,并在1go中执行以下操作:

  • 在MySecondClasses集合中创建2个新的Secondclass对象(两者的id均为0)
  • 将这些新创建的对象之一设置为SelectedSecondClass
然后英孚拒绝打球。我不能让它工作。如果我查看changetracker,我会看到实体上的SelectedSecondClass再次为空,但SelectedSecondClassId设置为0。这是他无法解决的问题,因为在正确创建之前,有两个Id为0的对象

如果我这样做,我可以把东西修好:

var newId = -1;
foreach (var newSecondClass in firstClass.MySecondClasses.Where(x => x.Id <= 0))
{
    newSecondClass.Id = newId;
    newId --;
}

if (firstClass.SelectedSecondClass != null) 
{ 
    firstClass.SelectedSecondClassId = firstClass.SelectedSecondClass.Id;
}

// Send the updates to EF
var newId=-1;
firstClass.mysecondclass.Where(x=>x.Id)中的foreach(var newSecondClass