0
votes

Consider I have 2 entities - a) Publisher b) Book Publisher has navigation property called as PublishedBooks which is collection of Books. Assume that Publisher1 has published 2 books ie Book1 & Book2 What I would like to do is, for a Publisher1, delete published book Book1 and add a new published book (ie Book3), in the database.

Context.SaveChanges() throwing below 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 deleted.

Note : Delete cascade rule is present in database as well as in the context class. BTW, I am using C# & Sql Server 2005.

2
// I am trying to remove the book from the Publisher's book collection as - Publiser1.Books.Remove(Publisher1.Books.First()); // then add a new book to the same collection as - var newbook = new book(){}; Publiser1.Books.Add(newbook); Context.SaveChanges();Gopal Tayde
Thanks but please add the code to your question. Also show the Book and Publisher class so other people know how you have implemented it currently. So they can correct you if you have some mistakes in the code ;)hwcverwe
sure will create a poc and upload itGopal Tayde

2 Answers

0
votes

Sounds like you are doing something like this:

Foo foo = entity.RelatedFoos.Where(f=>f.id=xyz);
entity.RelatedFoos.Remove(foo); //this is the problematic line
context.SaveChanges();

That is; you are removing an entity from a set of related items - not from the main collection on the context itself. As noted in the error, removing the above way only removes the relation. Not the object foo. This is probably what you meant, if you mean to delete the foo:

Foo foo = entity.RelatedFoos.Where(f=>f.id=xyz);
context.Foos.Remove(foo);
context.SaveChanges();
0
votes

You need to explicitly delete the child object before the save, e.g.

Context.DeleteObject(Book1);
Context.SaveChanges();