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

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

    I just had the same error. I have two tables with a parent child relationship, but I configured a "on delete cascade" on the foreign key column in the table definition of the child table. So when I manually delete the parent row (via SQL) in the database it will automatically delete the child rows.

    However this did not work in EF, the error described in this thread showed up. The reason for this was, that in my entity data model (edmx file) the properties of the association between the parent and the child table were not correct. The End1 OnDelete option was configured to be none ("End1" in my model is the end which has a multiplicity of 1).

    I manually changed the End1 OnDelete option to Cascade and than it worked. I do not know why EF is not able to pick this up, when I update the model from the database (I have a database first model).

    For completeness, this is how my code to delete looks like:

       public void Delete(int id)
        {
            MyType myObject = _context.MyTypes.Find(id);
    
            _context.MyTypes.Remove(myObject);
            _context.SaveChanges(); 
       }    
    

    If I hadn´t a cascade delete defined, I would have to delete the child rows manually before deleting the parent row.

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

    This type of solution did the trick for me:

    Parent original = db.Parent.SingleOrDefault<Parent>(t => t.ID == updated.ID);
    db.Childs.RemoveRange(original.Childs);
    updated.Childs.ToList().ForEach(c => original.Childs.Add(c));
    db.Entry<Parent>(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.

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

    This issue arise because we try to delete the parent table still child table data is present. We solve the problem with help of cascade delete.

    In model Create method in dbcontext class.

     modelBuilder.Entity<Job>()
                    .HasMany<JobSportsMapping>(C => C.JobSportsMappings)
                    .WithRequired(C => C.Job)
                    .HasForeignKey(C => C.JobId).WillCascadeOnDelete(true);
                modelBuilder.Entity<Sport>()
                    .HasMany<JobSportsMapping>(C => C.JobSportsMappings)
                      .WithRequired(C => C.Sport)
                      .HasForeignKey(C => C.SportId).WillCascadeOnDelete(true);
    

    After that,In our API Call

    var JobList = Context.Job                       
              .Include(x => x.JobSportsMappings)                                     .ToList();
    Context.Job.RemoveRange(JobList);
    Context.SaveChanges();
    

    Cascade delete option delete the parent as well parent related child table with this simple code. Make it try in this simple way.

    Remove Range which used for delete the list of records in the database Thanks

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

    I found this answer much more helpful for the same error. It seems that EF does not like it when you Remove, it prefers Delete.

    You can delete a collection of records attached to a record like this.

    order.OrderDetails.ToList().ForEach(s => db.Entry(s).State = EntityState.Deleted);
    

    In the example, all of the Detail records attached to an Order have their State set to Delete. (In preparation to Add back updated Details, as part of an Order update)

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

    I used Mosh's solution, but it was not obvious to me how to implement the composition key correctly in code first.

    So here is the solution:

    public class Holiday
    {
        [Key, Column(Order = 0), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int HolidayId { get; set; }
        [Key, Column(Order = 1), ForeignKey("Location")]
        public LocationEnum LocationId { get; set; }
    
        public virtual Location Location { get; set; }
    
        public DateTime Date { get; set; }
        public string Name { get; set; }
    }
    
    0 讨论(0)
  • 2020-11-22 05:21

    This happens because the Child Entity is marked as Modified instead of Deleted.

    And the modification that EF does to the Child Entity when parent.Remove(child) is executed, is simply setting the reference to its parent to null.

    You can check the child's EntityState by typing the following code into Visual Studio's Immediate Window when the exception occurs, after executing SaveChanges():

    _context.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Modified).ElementAt(X).Entity
    

    where X should be replaced by the deleted Entity.

    If you don't have access to the ObjectContext to execute _context.ChildEntity.Remove(child), you can solve this issue by making the foreign key a part of the primary key on the child table.

    Parent
     ________________
    | PK    IdParent |
    |       Name     |
    |________________|
    
    Child
     ________________
    | PK    IdChild  |
    | PK,FK IdParent |
    |       Name     |
    |________________|
    

    This way, if you execute parent.Remove(child), EF will correctly mark the Entity as Deleted.

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