我已将对象附加到上下文,尽管我收到错误Cannot remove an entity that has not been attached.
if (itemRemove != -1)
{
//var deleteDetails = DBContext.ProductCustomizationMasters.Where(p => p.ProductID == this.ProductID && p.CustomCategoryID == catId && p.CustomType == (short)catTypeId).Single();
var deleteDetails = DBContext.ProductCustomizationMasters.Single(p => p.ProductID == this.ProductID && p.CustomCategoryID == catId && p.CustomType == (short)catTypeId);
DBContext.ProductCustomizationMasters.Attach(deleteDetails);
DBContext.ProductCustomizationMasters.DeleteOnSubmit(deleteDetails);
RemoveCategoryItems(catId, catTypeId);
}
private void RemoveCategoryItems(int catId, CategoryType catTypeId)
{
switch (catTypeId)
{
case CategoryType.Topping:
(this.ToppingItems.Where(xx => xx.ToppingInfo.CatID == catId && xx.ProductID == this.ProductID).Single()).IsDefault = false;
FreeToppingItems.RemoveAll(x => x.ProductID == this.ProductID && x.ToppingInfo.CatID == catId);
break;
case CategoryType.Dressing:
(this.DressingItems.Where(xx => xx.DressingInfo.CatID == catId && xx.ProductID == this.ProductID).Single()).IsDefault = false;
FreeDressingItems.RemoveAll(x => x.ProductID == this.ProductID && x.DressingInfo.CatID == catId);
break;
case CategoryType.SpecialInstruction:
(this.InstructionItems.Where(xx => xx.InstructionInfo.CatID == catId && xx.ProductID == this.ProductID).Single()).IsDefault = false;
FreeInstructionItems.RemoveAll(x => x.ProductID == this.ProductID && x.InstructionInfo.CatID == catId);
break;
}
}
答案 0 :(得分:1)
第一个IDEA - 您无需附加要删除的项目。该项已附加到上下文,并且正在管理状态。只需跳过附加行并删除该对象。
编辑由于附件似乎不是您的问题,请试一试:
if (itemRemove != -1)
{
var deleteDetails = DBContext.ProductCustomizationMasters.Single(p => p.ProductID == this.ProductID && p.CustomCategoryID == catId && p.CustomType == (short)catTypeId);
//Obviously, this isn't going to work directly, you need to actually assign the ID, Primary Key Field here...
var deleteMe = new ProductCustomizationMasters() { PrimaryKey = deleteDetails.PrimaryKey };
DBContext.Attach(deleteMe);
DBContext.DeleteOnSubmit(deleteMe);
DBContext.SubmitChanges();
RemoveCategoryItems(catId, catTypeId);
}
再次编辑 - 您发布的代码似乎不是您问题的根源。此代码之外的某些内容正在设置一个对象,以便从尚未附加的上下文中删除。我建议您重新检查代码并检查所有对“DeleteOnSubmit”的引用,并确保在标记它们时附加这些实体。