Search code examples
mysqlentity-frameworkcascading-deletes

MySQL + Entity Framework: Can't delete object


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.


Solution

  • 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