使用原始 SQL 更改数据库内容会使 EntityFramework 上下文不同步

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

我有一个 table A 与另一个 table B 有外键关系。首先,我使用原始 SQL 删除 A 中的条目 (a)。后来我删除了tableB中的一个条目,b,这是a指向的条目。当我这样做时,EntityFramework 失败并显示错误消息:

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.

我认为这是因为上下文与数据库不同步。我该如何解决这个问题?

你的假设是对的。当您使用原始 SQL 更改数据库中的数据时,上下文不知道这些更改。来自 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.

您必须告诉 EntityFramework 从数据库更新上下文。这可以像这样完成(假设只有值 req 被这个 SQL 命令删除):

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