Entity Framework uses Set NULL on delete randomly.

Dimitar Kovachev 1 Reputation point
2021-01-07T20:10:56.277+00:00

Hello! I'm using EF 6.1.3 db first. As far as i know this configuration doesn't allow me to configure cascade deletion or set null on delete, so i haven't configure it on any FK. I have the following configuration: Table 2 has nullable FK to table 1, which makes it one to many relation. I noticed a strange anomaly: I was deleting a record from table 1 (when there is related record in table 2) which must throw error. However it doesn't. Afterall the record from table 1 is deleted and the FK column in table 2 is set to null. I compared similar configuration(one to many relation) in the same db from the same service and throws an error. I checked the properties in the sql server for those Fk's - they are the same - Delete Rule: No Action, which makes me believe the problem comes from EF. The wanted behavior is that EF just throws exception. What could cause this ambiguity in those very same actions?

Developer technologies .NET Other
{count} votes

1 answer

Sort by: Most helpful
  1. Daniel Zhang-MSFT 9,651 Reputation points
    2021-01-08T06:12:00.593+00:00

    Hi DimitarKovachev-5123,
    Maybe it is not implemented in the Entity Framework 6.
    And Dabblernl provieded a workaround that you can to load all the related entities in memory and then on deletion of the parent entity EF will issue SQL commands to set their foreign keys to Null.
    More details you can refer to this thread.
    Best Regards,
    Daniel Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.