他のオブジェクトと関係があるため、オブジェクトを削除する際に問題があります。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; }
}
そして、ここに私の Product Controller のコードがあります:
// 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 は、作業単位として構成された私のリポジトリ クラスです。
アプリを実行しようとすると、コレクションが変更されたと表示されるため、関係オブジェクトは削除されますが、製品オブジェクトは削除されません。
このコードを機能させるには、どのようにリファクタリングすればよいでしょうか。
前もって感謝します。