我正在尝试对多对多关系执行组合添加/更新功能。数据库优先。拥有三个sql表:Personnel、Orders、PersonnelOrders。这是我的代码:
context.ContextOptions.LazyLoadingEnabled = true;
if (saveData.Rows.Count() > 1)
{
foreach (var row in saveData.Rows)
{
if (row != null)
{
var Order_Array = row.Order_Array; //Array of order id's to be used below.
var pData = new Personnel;
{
Personnel_Id = row.Key,
Personnel_Name = row.Name
};
if (pData.Personnel_Id == 0) //ADD
{
foreach (int Id in Order_Array)
{
pData.Orders.Add(new Order() { Order_Id = Id });
}
context.Personnel.AddObject(cvData);
foreach (var j in pData.Orders)
{
context.ObjectStateManager.ChangeObjectState(j, EntityState.Unchanged);
}
}
else //Doesn't error out, but does not work either:
{
pData.Orders.Clear();
foreach (int Id in Order_Array)
{
pData.Orders.Add(new Order() { Order_Id = Id });
}
context.Personnel.Attach(cvData);
context.ObjectStateManager.ChangeObjectState(pData, EntityState.Modified);
}
context.SaveChanges();
}
}
}
return "ok";
编辑:我让 ADD 工作,现在我被困在UPDATE上。请参阅上面的修改后的代码。