MySQL +实体框架:无法删除对象

发布于 2024-12-01 02:54:14 字数 725 浏览 6 评论 0原文

我试图通过实体框架(MySQL/连接器)删除具有外键关系的对象。

客户帐户 >>> ClientEmailAddresses

  foreach (ClientAccount client in recsClientStore.Deleted) {   
        ClientAccount stub = new ClientAccount();
        stub.Id = client.Id;
        this.DBContext.AttachTo("ClientAccounts", stub);


        stub.FkClientEmailAddresses.Clear();
        this.DBContext.DeleteObject(stub);
    }

    this.DBContext.SaveChanges();

..但是当我这样做时,出现以下错误:

操作失败:无法更改关系,因为 一个或多个外键属性不可为 null。当一个 对关系进行更改时,相关的外键属性是 设置为空值。如果外键不支持空值, 必须定义一个新的关系,外键属性必须是 分配另一个非空值,或者不相关的对象必须是 已删除。

我不太确定这会让我做什么。我必须先删除 EmailAddress 对象吗?我们对打开级联持谨慎态度,但看起来越来越像是清理外键所必需的。

I'm trying to delete an object that has foreign key relationships via the Entity Framework (MySQL/Connector).

ClientAccount >>> ClientEmailAddresses

  foreach (ClientAccount client in recsClientStore.Deleted) {   
        ClientAccount stub = new ClientAccount();
        stub.Id = client.Id;
        this.DBContext.AttachTo("ClientAccounts", stub);


        stub.FkClientEmailAddresses.Clear();
        this.DBContext.DeleteObject(stub);
    }

    this.DBContext.SaveChanges();

.. but when I do this I get the following error:

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.

I'm not really sure where this leaves me. Do I have to delete the EmailAddress object first? We're wary of turning on cascade but it's looking more and more like this is required to tidy up foreign keys.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

Saygoodbye 2024-12-08 02:54:14

问题是:

stub.FkClientEmailAddresses.Clear();

不会删除关系。它只是将相关实体中的FK设置为​​null。如果您希望它们真正删除,则必须:

  • 通过在其对象集上调用 Remove 来删除它们
  • 更改与 识别关系 - 这将使Clear按预期工作
  • 正确设置级联删除EDMX 和数据库,并且根本不调用 Clear

The problem is that this:

stub.FkClientEmailAddresses.Clear();

doesn't delete relations. It only set FK in related entities to null. If you want them really delete you must either:

  • Delete them by calling Remove on their object set
  • Change relation to identifying relationship - that will make Clear work as expected
  • Correctly setup cascade delete in both EDMX and database and do not call Clear at all
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文