【发布时间】:2012-11-20 12:45:34
【问题描述】:
我正在使用 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
}
}
【问题讨论】:
-
看来你没有调用 EF 的 SaveChanges
-
我猜有一个表叫Target。此表具有对 Comments 表的 FK 引用。当您尝试删除 Comment 表中的行时,需要先删除 Target 中的关联行。
-
@Nagg 我在调用 SubmitChanges() 时收到此错误
-
@ErcFan 不,我没有表,我认为这是实体框架创建的默认关系名称。 (我使用的是代码优先)
-
@RaraituL 你能解释更多代码吗?
标签: c# entity-framework ef-code-first domain-driven-design