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

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

    This type of solution did the trick for me:

    Parent original = db.Parent.SingleOrDefault(t => t.ID == updated.ID);
    db.Childs.RemoveRange(original.Childs);
    updated.Childs.ToList().ForEach(c => original.Childs.Add(c));
    db.Entry(original).CurrentValues.SetValues(updated);
    

    Its important to say that this deletes all the records and insert them again. But for my case (less then 10) it´s ok.

    I hope it helps.

提交回复
热议问题