我正在尝试通过 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();
.. 但是当我这样做时,出现以下错误:
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.
我不太确定这会把我留在哪里。我必须先删除 EmailAddress 对象吗?我们对打开级联持谨慎态度,但它看起来越来越像需要整理外键。
最佳答案
问题在于:
stub.FkClientEmailAddresses.Clear();
不删除关系。它只将相关实体中的 FK 设置为 null。如果你想让它们真正删除,你必须:
- 通过在它们的对象集上调用
Remove
来删除它们 - 更改与 identifying relationship 的关系- 这将使
Clear
按预期工作 - 在 EDMX 和数据库中正确设置级联删除,根本不调用 Clear
关于MySQL + Entity Framework : Can't delete object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7160357/