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

前端 未结 20 1328
情书的邮戳
情书的邮戳 2020-11-22 04:44

I am getting this error when I GetById() on an entity and then set the collection of child entities to my new list which comes from the MVC view.

The

20条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 05:07

    I've tried these solutions and many others, but none of them quite worked out. Since this is the first answer on google, I'll add my solution here.

    The method that worked well for me was to take relationships out of the picture during commits, so there was nothing for EF to screw up. I did this by re-finding the parent object in the DBContext, and deleting that. Since the re-found object's navigation properties are all null, the childrens' relationships are ignored during the commit.

    var toDelete = db.Parents.Find(parentObject.ID);
    db.Parents.Remove(toDelete);
    db.SaveChanges();
    

    Note that this assumes the foreign keys are setup with ON DELETE CASCADE, so when the parent row is removed, the children will be cleaned up by the database.

提交回复
热议问题