none
[EF 6.1.3] How to delete parent and child when in the database I have not set the delete on cascade? RRS feed

  • Question

  • I know that when I do a saveChanges(), EF does not ensure the order of the t-sql, so it could try to delete the parent before to delete the child so I get an error about the reference integrity.

    By the moment the logic and decision of what I want to delete I prefer to have it in one place, so in my case I would like to have in my repository and not to have the cascade on delete in the relationship in the database, but if I choose this option, how is the best way to delete parents and childs with EF?

    I could try to use many saveChanges, but I think that I lost performance because I make more calls to the database.

    thank you so much.

    Friday, March 11, 2016 12:22 PM

Answers

  • By the moment the logic and decision of what I want to delete I prefer to have it in one place, so in my case I would like to have in my repository and not to have the cascade on delete in the relationship in the database, but if I choose this option, how is the best way to delete parents and childs with EF?

    Delete all the children objects first before deleting the parent, just like you would do it if you doing it T-SQL in deleting all children records and then the parent record.

      

    Friday, March 11, 2016 1:03 PM

All replies

  • By the moment the logic and decision of what I want to delete I prefer to have it in one place, so in my case I would like to have in my repository and not to have the cascade on delete in the relationship in the database, but if I choose this option, how is the best way to delete parents and childs with EF?

    Delete all the children objects first before deleting the parent, just like you would do it if you doing it T-SQL in deleting all children records and then the parent record.

      

    Friday, March 11, 2016 1:03 PM
  • After searching, I have found that I can set this in the mapping of the entities. This is the documentation:
    https://msdn.microsoft.com/en-us/data/jj591620.aspx#CascadeDelete


    However, the problem is when it says this:

    "If a foreign key on the dependent entity is nullable, Code First does not set cascade delete on the relationship, and when the principal is deleted the foreign key will be set to null".

    IN my case the FK allows null values, but I want to delete the child instead to set to null, so in my case it seems that the best option it is to set the cascade deletion in the database.

    Monday, March 14, 2016 8:21 AM