[英]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. 该实体具有列表表的外键,但我可以从Heidi MySql客户端删除数据库条目而不会出现问题。
I'm trying to clear the child entities, but when i call SaveChanges on the context, it throws the mentioned error. 我正在尝试清除子实体,但是当我在上下文中调用SaveChanges时,它将引发所提到的错误。
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. 在导航属性上使用.Clear()
不会将它们从数据库中删除,只会清除代码中的集合。 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. 另一种可能性是启用级联删除功能,该功能允许在删除父实体的情况下删除子实体。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.