Tony Tony - 1 year ago 276
C# Question

Entity Framework on delete cascade

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:

ALTER TABLE [dbo].[BookFormats] WITH CHECK ADD CONSTRAINT [FK_BookFormats_Book]
FOREIGN KEY([BookID]) REFERENCES [dbo].[Book] ([BookID]) on delete cascade

The EDMX property

enter image description here

Then, I want to remove the all
items related to my

var originalBook = m.db.Book.First(x => x.BookID == bookId);

But, I get the error:

The operation failed: The relationship could not be changed because
one or more of the foreign-key properties is non-nullable. When a
change is made to a relationship, the related foreign-key property is
set to a null value. If the foreign-key does not support null values,
a new relationship must be defined, the foreign-key property must be
assigned another non-null value, or the unrelated object must be

I ran out of ideas on how to delete these objects. Any ideas?

Answer Source

Cascade deletions concept is as follows:

When you delete Book from the DB all related BookFormats will be deleted for you by SQL Server (please note that it doesn't matter how deletion of Book will be initiated via EF or raw SQL). Thus it has nothing to do with your task: "I want to delete all BookFormats related to my Book". To accomplish it you need somethind like this:

foreach(var m in m.db.BookFormats.Where(f=>f.BookID = bookID))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download