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

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

    If you are using Auto mapper and facing the the issue following is the good solution, it work for me

    https://www.codeproject.com/Articles/576393/Solutionplusto-aplus-Theplusoperationplusfailed

    Since the problem is that we're mapping null navigation properties, and we actually don't need them to be updated on the Entity since they didn't changed on the Contract, we need to ignore them on the mapping definition:

    ForMember(dest => dest.RefundType, opt => opt.Ignore())
    

    So my code ended up like this:

    Mapper.CreateMap<MyDataContract, MyEntity>
    ForMember(dest => dest.NavigationProperty1, opt => opt.Ignore())
    ForMember(dest => dest.NavigationProperty2, opt => opt.Ignore())
    .IgnoreAllNonExisting();
    
    0 讨论(0)
  • 2020-11-22 05:24

    The reason you're facing this is due to the difference between composition and aggregation.

    In composition, the child object is created when the parent is created and is destroyed when its parent is destroyed. So its lifetime is controlled by its parent. e.g. A blog post and its comments. If a post is deleted, its comments should be deleted. It doesn't make sense to have comments for a post that doesn't exist. Same for orders and order items.

    In aggregation, the child object can exist irrespective of its parent. If the parent is destroyed, the child object can still exist, as it may be added to a different parent later. e.g.: the relationship between a playlist and the songs in that playlist. If the playlist is deleted, the songs shouldn't be deleted. They may be added to a different playlist.

    The way Entity Framework differentiates aggregation and composition relationships is as follows:

    • For composition: it expects the child object to a have a composite primary key (ParentID, ChildID). This is by design as the IDs of the children should be within the scope of their parents.

    • For aggregation: it expects the foreign key property in the child object to be nullable.

    So, the reason you're having this issue is because of how you've set your primary key in your child table. It should be composite, but it's not. So, Entity Framework sees this association as aggregation, which means, when you remove or clear the child objects, it's not going to delete the child records. It'll simply remove the association and sets the corresponding foreign key column to NULL (so those child records can later be associated with a different parent). Since your column does not allow NULL, you get the exception you mentioned.

    Solutions:

    1- If you have a strong reason for not wanting to use a composite key, you need to delete the child objects explicitly. And this can be done simpler than the solutions suggested earlier:

    context.Children.RemoveRange(parent.Children);
    

    2- Otherwise, by setting the proper primary key on your child table, your code will look more meaningful:

    parent.Children.Clear();
    
    0 讨论(0)
  • 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<A, A>(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<A, A>()
         .ForMember(m => m.ClassB, opt => opt.Ignore()); // We use the ClassBId
    
    0 讨论(0)
  • 2020-11-22 05:30

    I also solved my problem with Mosh's answer and I thought PeterB's answer was a bit of since it used an enum as foreign key. Remember that you will need to add a new migration after adding this code.

    I can also recommend this blog post for other solutions:

    http://www.kianryan.co.uk/2013/03/orphaned-child/

    Code:

    public class Child
    {
        [Key, Column(Order = 0), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
    
        public string Heading { get; set; }
        //Add other properties here.
    
        [Key, Column(Order = 1)]
        public int ParentId { get; set; }
    
        public virtual Parent Parent { get; set; }
    }
    
    0 讨论(0)
  • 2020-11-22 05:31

    I've no idea why the other two answers are so popular!

    I believe you were right in assuming the ORM framework should handle it - after all, that is what it promises to deliver. Otherwise your domain model gets corrupted by persistence concerns. NHibernate manages this happily if you setup the cascade settings correctly. In Entity Framework it is also possible, they just expect you to follow better standards when setting up your database model, especially when they have to infer what cascading should be done:

    You have to define the parent - child relationship correctly by using an "identifying relationship".

    If you do this, Entity Framework knows the child object is identified by the parent, and therefore it must be a "cascade-delete-orphans" situation.

    Other than the above, you might need to (from NHibernate experience)

    thisParent.ChildItems.Clear();
    thisParent.ChildItems.AddRange(modifiedParent.ChildItems);
    

    instead of replacing the list entirely.

    UPDATE

    @Slauma's comment reminded me that detached entities are another part of the overall problem. To solve that, you can take the approach of using a custom model binder that constructs your models by attempting to load it from the context. This blog post shows an example of what I mean.

    0 讨论(0)
  • 2020-11-22 05:32

    I had same problem, but I knew it had worked OK in other cases, so I reduced the problem to this:

    parent.OtherRelatedItems.Clear();  //this worked OK on SaveChanges() - items were being deleted from DB
    parent.ProblematicItems.Clear();   // this was causing the mentioned exception on SaveChanges()
    
    • OtherRelatedItems had a composite Primary Key (parentId + some local column) and worked OK
    • ProblematicItems had their own single-column Primary Key, and the parentId was only a FK. This was causing the exception after Clear().

    All I had to do was to make the ParentId a part of composite PK to indicate that the children can't exist without a parent. I used DB-first model, added the PK and marked the parentId column as EntityKey (so, I had to update it both in DB and EF - not sure if EF alone would be enough).

    Once you think about it, it's a very elegant distinction that EF uses to decide if children "make sense" without a parent (in this case Clear() won't delete them and throw exception unless you set the ParentId to something else/special), or - like in the original question - we expect the items to be deleted once they are removed from the parent.

    0 讨论(0)
提交回复
热议问题