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
。コメントは製品なしでは存在できないため、Product
Aggregateの子であり、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
}
}