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

}

そして、ここに私の 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 は、作業単位として構成された私のリポジトリ クラスです。

アプリを実行しようとすると、コレクションが変更されたと表示されるため、関係オブジェクトは削除されますが、製品オブジェクトは削除されません。

このコードを機能させるには、どのようにリファクタリングすればよいでしょうか。

前もって感謝します。

4

1 に答える 1

1

を使用している場合、基になるコレクションを変更することはできません。基本的なステートメントforeachを使用することをお勧めします。for

上記の MSDN リンクから:

foreach ステートメントは、コレクションを反復処理して必要な情報を取得するために使用されますが、予期しない副作用を避けるために、ソース コレクションからアイテムを追加または削除するために使用することはできません。ソース コレクションからアイテムを追加または削除する必要がある場合は、for ループを使用します。

于 2013-01-12T22:41:17.210 に答える