9

DDDを使用しています。集約ルートであるクラス Product があります。

public class Product : IAggregateRoot
{
    public virtual ICollection<Comment> Comments { get; set; }

    public void AddComment(Comment comment)
    {
        Comments.Add(comment);
    }

    public void DeleteComment(Comment comment)
    {
        Comments.Remove(comment);
    }
}

モデルを保持するレイヤーは、EF についてまったく知りません。問題は、私が呼び出すとDeleteComment(comment)、EFが例外をスローすることです

「Product_Comments」AssociationSet からの関係は「削除済み」状態です。多重度の制約がある場合、対応する「Product_Comments_Target」も「削除済み」状態でなければなりません。

要素がコレクションから削除されても、EF はそれを削除しません。DDD を壊さずにこれを修正するにはどうすればよいですか? (コメント用のリポジトリも作ろうと思っているのですが、ダメです)

コード例:

私は DDD を使用しようとしているため、これProductは集約ルートであり、リポジトリがありますIProductRepository。コメントは製品なしでは存在できないため、ProductAggregateの子であり、Productコメントの作成と削除を担当します。Commentにはリポジトリがありません。

public class ProductService
{
    public void AddComment(Guid productId, string comment)
    {
        Product product = _productsRepository.First(p => p.Id == productId);
        product.AddComment(new Comment(comment));
    }

    public void RemoveComment(Guid productId, Guid commentId)
    {
        Product product = _productsRepository.First(p => p.Id == productId);
        Comment comment = product.Comments.First(p => p.Id == commentId);
        product.DeleteComment(comment);


        // Here i get the error. I am deleting the comment from Product Comments Collection,
        // but the comment does not have the 'Deleted' state for Entity Framework to delete it

        // However, i can't change the state of the Comment object to 'Deleted' because
        // the Domain Layer does not have any references to Entity Framework (and it shouldn't)

        _uow.Commit(); // UnitOfWork commit method

    }
}
4

5 に答える 5

6

関連するソリューションのペアを次に示します。

EF コレクションから削除されたときに依存エンティティを削除する

于 2012-11-21T09:07:41.390 に答える
1

アプローチを使用して製品からコメントを削除すると、製品とコメントの間の関連付けのみが削除されます。コメントがまだ存在するように。

あなたがする必要があるのは、メソッドを使用して Comment も削除されることを ObjectContext に伝えることですDeleteObject()

私が行う方法は、リポジトリの Update メソッド (Entity Framework を知っている) を使用して、削除された関連付けをチェックし、古いエンティティも削除することです。これは、ObjectContext の ObjectStateManager を使用して行うことができます。

public void UpdateProduct(Product product) {
  var modifiedStateEntries = Context.ObjectStateManager.GetObjectStateEntries(EntityState.Modified);
    foreach (var entry in modifiedStateEntries) {
      var comment = entry.Entity as Comment;
      if (comment != null && comment.Product == null) {
        Context.DeleteObject(comment);
      }
    }
 }

サンプル:

public void RemoveComment(Guid productId, Guid commentId) {
  Product product = _productsRepository.First(p => p.Id == productId);
  Comment comment = product.Comments.First(p => p.Id == commentId);
  product.DeleteComment(comment);

  _productsRepository.Update(product);

  _uow.Commit();
}
于 2012-11-21T07:20:18.360 に答える
0

モデルの親属性を作成し、SaveChanges 関数で属性を確認することで、同じ問題を解決しました。これについてブログを書きました: http://wimpool.nl/blog/DotNet/extending-entity-framework-4-with-parentvalidator

于 2012-11-21T10:01:09.190 に答える