Entity framework 在EF 5中为新对象使用循环外键引用的更好方法
我在一个web项目中首先使用EF5.0和DB 对于我们的服务层,我们使用Agatha和AutoMapper,因此所有数据都作为POCO对象到达服务层 我的数据结构如下所示: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
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
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