简体   繁体   中英

Entity Framework 5 The relationship could not be changed because one or more of the foreign-key properties is non-nullable

I receive the fore mentioned error when trying to delete an entity.

This entity has a foreign key to a list table, but I can delete the DB entry without a problem from Heidi MySql client.

I'm trying to clear the child entities, but when i call SaveChanges on the context, it throws the mentioned error.

nquote_orderheaders header = portalDb.nquote_orderheaders.Single(f => f.QuoteOrderNumber == id);

        header.nquote_orderlines.Clear();
        portalDb.SaveChanges();
        portalDb.nquote_orderheaders.Remove(header);
        portalDb.SaveChanges();

Using .Clear() on a navigation property doesn't remove them from the database, it only clears your collection in your code. You need to iterate over your orderlines to remove them one by one.

Another possibility is to enable cascading delete feature, which allows child entities removal if parent entity is removed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM