I am using DDD. I have a Product class, which is an aggregated root.
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); } }
The layer that contains the models does not know about EF at all. The problem is that when I call DeleteComment(comment) , EF throws an exception
The Product_Comments Product Range relationship is in the Deleted state. Given the limitations of multiplicity, the corresponding "Product_Comments_Target" must also be in the "Deleted" state.
Even if an item is removed from the collection, EF does not delete it. What should I do to fix this without breaking DDD? (I also want to create a repository for comments, but not right)
Code example:
Since I'm trying to use DDD, Product is an aggregated root and has an IProductRepository repository. A comment cannot exist without a product, therefore it is a child of Product Aggregate, and Product is responsible for creating and deleting comments. Comment does not have a repository.
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);
Catalin
source share