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是結構爲工作單位的我的倉庫類。
當我嘗試運行應用程序時,它刪除關係對象,但不刪除產品對象,因爲它表示該集合已被修改。
我應該如何重構這個代碼,使其工作É
在此先感謝。
我會嘗試刪除第一個'Uow.Commit()'並在最後只做一個。 – mipe34