我在删除对象时遇到问题,因为它与其他对象有关系。我正在使用 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 是一个我的存储库类,其结构为一个工作单元。
当我尝试运行应用程序时,它会删除关系对象,但不会删除产品对象,因为它说 Collection 已被修改。
我应该如何重构此代码以使其正常工作É
提前致谢。