none
Simplest way to delete multiple rows from multiple tables in EF 5 RRS feed

  • Question

  • Hi guys,

    I'm working with multiple entities which are related.

    When I want to delete a row, I will have to delete all it's related rows from the other tables.

    That could be done by searching all the related rows, and then delete them one by one..

    Is there any better solution, with less code ?

    Tuesday, March 5, 2013 1:45 PM

All replies

  • Hi,

    You could also handle them database side

    Try http://stackoverflow.com/questions/12954104/willcascadeondelete-in-netmvc4-is-not-working (or http://stackoverflow.com/questions/5448702/cascading-deletes-with-entity-framework-related-entities-deleted-by-ef if you really prefer client side with EF)


    Please always mark whatever response solved your issue so that the thread is properly marked as "Answered".

    Tuesday, March 5, 2013 1:56 PM
  • Hi Houssem;

    Doing it on the server by using the CASCADE ON DELETE as Patrice links show will give greater performance.

      


    Fernando (MCSD)

    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    Tuesday, March 5, 2013 3:09 PM
  • Setting the relation with "ON DELETE -> Cascade" solution just won't work for me !
    Tuesday, March 5, 2013 4:15 PM
  • Hi Houssem;

    Well then that leaves you with the only other alternative which is to set the relationship on the parent side to "ON DELETE -> Cascade" between the two tables. Then in order for this to work you must have all related child entities in local memory / DbContext as well as the parent entity. Then by deleting the parent entity all load child entities will also be deleted. Please be advised that doing it this way will cause the Entity Framework to delete each of the entities child and parent one at a time.

      


    Fernando (MCSD)

    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    Tuesday, March 5, 2013 4:40 PM
  • Won't work because? Do you use code first or db first ? Which deletion method do you want to use (server side is fine or are you restricted to client side) ?

    Please always mark whatever response solved your issue so that the thread is properly marked as "Answered".

    Wednesday, March 6, 2013 12:55 PM
  • I'm using model first approach. I tried that feature ( "On Delete -> Cascade" )

    on the side of Entity1, on deleting Entity1, it won't delete the related Entity2 !

    I chooses to write more code, then dealing with functionality that lucks good 

    documentation !

    Thank you a lot Patrice and Fernando for your help.

    Wednesday, March 6, 2013 2:13 PM