gpt4 book ai didi

c# - 在 Entity Framework 中删除聚合根的子对象

转载 作者:行者123 更新时间:2023-12-05 04:17:13 27 4
gpt4 key购买 nike

之前可能有人问过这个问题,但我似乎无法在网站上找到解决方案,所以我们开始吧:

这是我的领域模型的一个过于简化的版本。我有 2 个类代表数据库中的 2 个表:

public Class Person
{
public int Id { get; set;}
public string Name { get; set;}
public virtual List<Contact> Contacts { get; set;}

public void AddContact(string value)
{
//some validation code
Contacts.Add(new Contact(value));
}

public void DeleteContact(Contact contact)
{
//some validation code
Contacts.Remove(contact);
}
}

public Class Contact
{
public int Id { get; set;}
public string Value { get; set;}
public virtual Person Person { get; set;}
public int PersonId { get; set;}
}

现在 Person 是我的聚合根。我试图通过只为聚合根创建存储库来遵循 DDD 原则。添加联系人工作正常。

我遇到的问题是删除联系人时。它给出了错误:

The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.

有没有过去呢。如果关系属性不可为空, Entity Framework 不应自动删除联系人。

现在我知道从集合中删除与从上下文中删除它不同,但我不想从我的域模型中引用 DbContext。

我只有 PersonRepository。

如果我有任何概念错误,请提供解决方案或帮助我理解。

最佳答案

这是使用 EF 执行 DDD 时的常见问题。到目前为止,有两种解决方案对我来说效果很好:

  1. 从您的 DeleteContact 方法中返回删除的实例。该方法很可能是从拥有存储库的应用程序服务调用的。然后您可以使用它从 DbContext 中删除实例。

  2. 如果您使用 domain events您可以使用一个通知其他人删除联系人。然后,您可以在基础架构层中放置此事件的处理程序,这将从 DbContext 中删除联系人。

关于c# - 在 Entity Framework 中删除聚合根的子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24601652/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com