2013-01-12 34 views
0

我有删除对象的问题,因为它与其他对象有关系。 我正在使用MVC4和Code First数据库方法。集合被修改错误

这里是我的模型类:

public class Product 
{ 
    public Product() { } 

    public int Id { get; set; } 
    public string Name { get; set; } 
    public decimal Price { get; set; } 
    public bool Istaxable { get; set; } 
    public string DefaultImage { get; set; } 
    public IList<Feature> Features { get; set; } 
    public IList<Descriptor> Descriptors { get; set; } 
    public IList<Category> Categories { get; set; } 
    public IList<Image> Images { get; set; } 

    public Product(string name, decimal price, bool istaxable, string defaultImageFile) 
    { 
     Name = name; 
     Price = price; 
     Istaxable = istaxable; 
     DefaultImage = defaultImageFile; 
     Categories = new List<Category>(); 
     Features = new List<Feature>(); 
     Descriptors = new List<Descriptor>(); 
     Images = new List<Image>(); 
    } 
} 

public class Image 
{ 

    public Image() { } 

    public Image(string thumb, string full) : this(thumb, full, false) { } 

    public Image(string thumb, string full, bool isDefault) 
    { 
     Thumb = thumb; 
     IsDefault = isDefault; 
     Full = full; 
    } 

    public int Id { get; set; } 
    public string Thumb { get; set; } 
    public string Full { get; set; } 
    public bool IsDefault { get; set; } 
    public string Description { get; set; } 

} 

这里是我的产品控制器代码:

// DELETE /api/product/5 
    public HttpResponseMessage Delete(int id) 
    { 

     var prd = Uow.Products.GetProductByIdIncludeAll(id); 

     var images = prd.Images; 
     if (images.Count > 0) 
     { 
      foreach(Image i in images) 
      { 
       Uow.Images.Delete(i); 
      } 
     } 

     var descriptors = prd.Descriptors; 
     if (descriptors.Count > 0) 
     { 
      foreach (Descriptor d in descriptors) 
      { 
       Uow.Descriptors.Delete(d); 
      } 
     } 

     var features = prd.Features; 
     if (features.Count > 0) 
     { 
      foreach (Feature f in features) 
      { 
       Uow.Features.Delete(f); 
      } 
     } 

     Uow.Commit(); 

     Uow.Products.Delete(id); 
     Uow.Commit(); 

     return new HttpResponseMessage(HttpStatusCode.NoContent); 
    }  

UOW是结构为工作单位的我的仓库类。

当我尝试运行应用程序时,它删除关系对象,但不删除产品对象,因为它表示该集合已被修改。

我应该如何重构这个代码,使其工作É

在此先感谢。

+0

我会尝试删除第一个'Uow.Commit()'并在最后只做一个。 – mipe34

回答

1

当您使用foreach时,您无法更改基础集合,我建议您使用基本的for语句。

从上面MSDN链接:

foreach语句被用于通过收集迭代,以获得您想要的信息,但不能用于从源集合添加或删除项目,以避免不可预知的副作用。如果您需要添加或删除源集合中的项目,请使用for循环