我正在使用DDD。我有一個類聚合的根產品。使用實體框架從集合中刪除項目
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
總計的子女,而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 – Nagg
我想有一個名爲目標的表。此表格具有FK對評論表的引用。當您嘗試刪除評論表中的行時,需要首先刪除目標中的關聯行。 –
@Nagg當我打電話SubmitChanges() – Catalin