Entity Framework on delete cascade

前端 未结 5 888
天涯浪人
天涯浪人 2020-12-10 03:31

I have problem with deleting related rows in Entity Framework 4.1. I have tables with relations

Book 1<--->* BookFormats

I have set the on delete cascade

5条回答
  •  伪装坚强ぢ
    2020-12-10 03:46

    You are not deleting the BookFormats from the database, but you are removing the relationship, thus orpahning your BookFormats and setting the BookID column to NULL. The delete cascade you have put on the database says When I delete theBook, then delete all of theBookFormatsthat have aBookIDequal to mine. You are not deleting the book you are deleting the formats from the Book.

    Instead of originalBook.BookFormats.Clear() you should have something like this...

    List idsToDelete = new List();
    
    foreach (BookFormat bf in originalBook.BookFormats)
    {
        idsToDelete.Add(bf.ID);
    }
    
    foreach (int id in idsToDelete)
    {
        BookFormat format = m.db.BookFormat.FirstOrDefault(x => x.ID == id);
        if (format != null)
        {
             m.db.DeleteBookFormat(format);
        }
    }
    
    m.db.SaveChanges();
    

    It should be something along those lines. I don't have it right in front of me to remember how EF constructs the delete method in the EDMX.

提交回复
热议问题