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

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

    If you are using AutoMapper with Entity Framework on the same class, you might hit this problem. For instance if your class is

    class A
    {
        public ClassB ClassB { get; set; }
        public int ClassBId { get; set; }
    }
    
    AutoMapper.Map(input, destination);
    

    This will try to copy both properties. In this case, ClassBId is non Nullable. Since AutoMapper will copy destination.ClassB = input.ClassB; this will cause a problem.

    Set your AutoMapper to Ignore ClassB property.

     cfg.CreateMap()
         .ForMember(m => m.ClassB, opt => opt.Ignore()); // We use the ClassBId
    

提交回复
热议问题