1

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?

Thorkil Værge
  • 2,727
  • 5
  • 32
  • 48

1 Answers1

0

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();
Thorkil Værge
  • 2,727
  • 5
  • 32
  • 48
  • What if I have made bulk update with ExecuteSqlRawAsync> How can I sync my dbcontext, please guide me. I am facing issue where new query still fetching old value. – Sahil M. Jan 02 '23 at 09:13