我对Entity Framework(4)有些新意,我有一个让我感到难过的特殊场景。我有两个基本实体:Cylinder
和Location
。两者之间有一对多的映射表。换句话说,Cylinder有一个Locations集合,一个Location有一个Cylinders集合。
我使用整数ID作为Cylinder和Location的Pk。
这些实体从同一上下文中检索为两个集合(Cylinders和Locations),并在客户端上进行编辑。编辑Cylinder.Location[0]
将更改Locations集合中的相应位置,即它是同一个对象。
现在,当需要保存在服务器上时,我的“更新”方法会获取一个Cylinders列表和一个Locations列表。独立保存气缸和位置非常简单。
更新:
我的初步方法如下:
//保存位置...
foreach (var cylinderLocation in cylinderLocations)
{
if (cylinderLocation.ChangeTracker.State == ObjectState.Added)
cylinderLocation.Insert();
else if (cylinderLocation.IsDirty)
cylinderLocation.Update();
}
// CylinderLocation.Insert()如下所示:
public static void Insert(this CylinderLocation cylinderLocation)
{
using (var context = new CylinderManagementModelContainer(GetConnectionString()))
{
if (cylinderLocation.Cylinder != null)
cylinderLocation.Cylinder.ModifiedTimeStamp = DateTime.Now;
cylinderLocation.ModifiedTimeStamp = DateTime.Now;
context.CylinderLocations.AddObject(cylinderLocation);
context.SaveChanges();
}
}
更新 CylinderLocation Insert()保存CylinderLocation和Cylinder(如果映射了一个);但是,当执行SaveCylinders步骤(下面)时,它仍然认为有一个Id = 0的新圆柱。换句话说,柱面[0] .Id = 0,但是位置[0] .Cylinder [0] .Id > 0
//保存圆柱......
foreach (var cylinder in cylinders)
{
if (cylinder.ChangeTracker.State == ObjectState.Added)
cylinder.Insert();
else if (cylinder.IsDirty)
cylinder.Update();
}
但是当我尝试保存新的Cylinder和一个新的位置并且它们都需要相互映射时,事情变得混乱。换句话说,Cylinder.Id = 0
,Location.Id = 0
并且它们都需要保存并相互映射。
我希望在保存发生后我可以更新ID(即使用属性更改并更新原始实体);然而,似乎一旦实体被序列化到服务器,Cylinder.Location[0]
不再是Locations集合中的同一对象,即它是一个不同的实例。所以Id更新不起作用。
我愿意接受任何建议。
感谢。