我正在尝试在多对多关系上执行组合的添加/更新功能。 DB首先。有三个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 。见上面的修订代码。
答案 0 :(得分:0)
这是我必须做的才能使它发挥作用。它对我来说看起来很难看,我确信它可以被改进,但它现在有效。
context.ContextOptions.LazyLoadingEnabled = true; //not sure that this is necessary
if (saveData.Rows.Count() > 1)
{
foreach (var row in saveData.Rows)
{
if (row != null)
{
var Order_Array = row.Order_Array;
if (row.Key == 0) //ADD
{
var pData = new Personnel;
{
Personnel_Id = row.Key, //probably not needed but it doesn't break it
Personnel_Name = row.Name
};
foreach (int Id in Order_Array)
{
var j = context.Orders.Where(c => c.Order_Id == Id).SingleOrDefault();
pData.Orders.Add(j);
}
context.Personnel.AddObject(pData);
foreach (var j in pData.Orders)
{
context.ObjectStateManager.ChangeObjectState(j, EntityState.Unchanged); //so that you don't actually add more orders
}
}
else //UPDATE
{
var ap = context.Personnel.FirstOrDefault(x => x.Personnel_Id == row.Key);
ap.Personnel_Name = row.Name;
ap.Orders.Clear(); //clear out existing associations
foreach (int Id in Order_Array)
{
var j = context.Orders.Where(c => c.Order_Id == Id).SingleOrDefault();
ap.Orders.Add(j); //rebuild new associations
}
}
context.SaveChanges();
}
}
}