entity-framework-corerawsql

Changing database content with raw SQL brings EntityFramework context out of sync


I have a table A that has a foreign key relation to another table B. First I delete an entry (a) in A using raw SQL. Later I delete an entry in table B, b, which was the entry that a was pointing to. When I do this, EntityFramework fails with the error message:

The association between entity types 'B' and 'A' has been severed but the relationship is either marked as 'Required' or is implicitly required because the foreign key is not nullable.

I assume that it is because the context gets out of sync with the database. How do I fix this?


Solution

  • You are right in your assumption. When you change data in the database using raw SQL, the context is unaware of these changes. From the documentation:

    Note that any changes made to data in the database using ExecuteSqlCommand are opaque to the context until entities are loaded or reloaded from the database.

    You have to tell EntityFramework to update the context from the database. This can be done like this (assuming only the value req is deleted by this SQL command):

    _db.Database.ExecuteSqlCommand($"DELETE FROM \"schema_name\".\"table_A\"");
    _db.Entry(req).Reload();