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

前端 未结 20 1068
情书的邮戳
情书的邮戳 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:10

    I ran into this problem today and wanted to share my solution. In my case, the solution was to delete the Child items before getting the Parent from the database.

    Previously I was doing it like in the code below. I will then get the same error listed in this question.

    var Parent = GetParent(parentId);
    var children = Parent.Children;
    foreach (var c in children )
    {
         Context.Children.Remove(c);
    }
    Context.SaveChanges();
    

    What worked for me, is to get the children items first, using the parentId (foreign key) and then delete those items. Then I can get the Parent from the database and at that point, it should not have any children items anymore and I can add new children items.

    var children = GetChildren(parentId);
    foreach (var c in children )
    {
         Context.Children.Remove(c);
    }
    Context.SaveChanges();
    
    var Parent = GetParent(parentId);
    Parent.Children = //assign new entities/items here
    

提交回复
热议问题