EF6.0 “The relationship could not be changed because one or more of the foreign-key properties is non-nullable”

眉间皱痕 提交于 2019-11-27 07:15:19

You need to delete the ItemTypeItem. It is not possible to just remove it from the Items list as it cannot exist by itself, because it has a non-nullable foreign key referencing ItemType (ItemTypeID).

To delete the ItemTypeItem add

context.Entry(itemTypeItem).State = EntityState.Deleted;
Gerry Polucci

In the entity framework 6.0 if you remove the entity from the main context set it will work. For example to remove an investment entity you would do the following:

context.Investments.Remove(entity);
context.SaveChanges();

This is different than attempting to remove the entity from its parent/owner, as the following:

bankAccount.Investments.Remove(entity);
context.SaveChanges();

This will throw the relationship could not be changed exception listed above. Hope this helps.

In entity 6.0 there is a difference between:

context.Investments.Remove(entity);

and

context.Entry(entity).State = EntityState.Deleted;

When using the first and cascading deletes are enabled, EF will internally perform the necessary deletes of child collections. When using the second option, EF will not handle the necessary deletes, but let you handle the rebinding/deletion of these child objects.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!