2

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.

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I think we're going to have re-examine our structure to establish whether we really need cascading.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.