-2

我已将对象附加到上下文,尽管我收到了错误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;
            }
        }
4

1 回答 1

1

第一个想法- 您不需要附加要删除的项目。该项目已附加到上下文并且正在管理状态。只需跳过附加线并删除对象。

编辑由于附件似乎不是您的问题,请试一试:

     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);
      }

再次编辑- 您发布的代码似乎不是问题的根源。这段代码之外有一些东西正在设置一个对象以从上下文中删除 ant 尚未附加。我建议重新检查您的代码并检查对“DeleteOnSubmit”的所有引用,并确保在标记它们时附加这些实体。

于 2013-08-12T14:36:17.400 回答