Remove an item from Collection using Entity Framework(使用实体框架从集合中删除项)
本文介绍了使用实体框架从集合中删除项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用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。评论没有产品就不能存在,因此是ProductAggregate的子级,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在这种情况下的预期行为。
诀窍:在设置父项和子项之间的关系时,您必须在子项上创建一个"复合"键。这样,当您告诉父级删除1个或所有子级时,相关记录实际上将从数据库中删除。使用Fluent API配置组合键:
modelBuilder.Entity<Child>.HasKey(t => new { t.ParentId, t.ChildId });
然后,删除相关子项:
var parent = _context.Parents.SingleOrDefault(p => p.ParentId == parentId);
var childToRemove = parent.Children.First(); // Change the logic
parent.Children.Remove(childToRemove);
// or, you can delete all children
// parent.Children.Clear();
_context.SaveChanges();
完成!
这篇关于使用实体框架从集合中删除项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:使用实体框架从集合中删除项
基础教程推荐
猜你喜欢
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
