我正在使用 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”关联集中的关系处于“已删除”状态。给定多重约束,相应的“Product_Comments_Target”也必须处于“已删除”状态。
即使从集合中删除元素,EF 也不会删除它。我应该怎么做才能在不破坏 DDD 的情况下解决这个问题?(我也在考虑为评论建立一个存储库,但不正确)
代码示例:
因为我正在尝试使用 DDD,所以Product
它是一个聚合根,它有一个存储库IProductRepository
。没有产品,评论就不能存在,因此是Product
聚合的孩子,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
}
}