实体框架RemoveRange不是CascadeDelete

时间:2016-11-17 10:36:00

标签: c# entity-framework

我有两个实体People和FollowUps,一对多关系,cascadedelete。如此处所定义(OnModelCreating):

modelBuilder.Entity<FollowUp>()
   .HasRequired(c => c.FollowUpPeople)
   .WithMany(p => p.FollowUps)
   .HasForeignKey(c => c.PersonID)
   .WillCascadeOnDelete(true);

我的模型实体是:

public class FollowUp {
   public int ID { get; set; }
   public int PersonID { get; set; }
   public virtual People FollowUpPeople { get; set; }
}

和人:

public class People {
    public int ID { get; set; }
    public virtual ICollection<FollowUp> FollowUps { get; set; }
}

当与人物实体一一删除时,级联删除工作正常。例如:

context.People.Remove(person1);
context.People.Remove(person2);
context.SaveChanges();

使用RemoveRange时我得到一个例外:

The operation failed: The relationship could not be changed because one or
more of the foreign-key properties is non-nullable. When a change is made to a
relationship, the related foreign-key property is set to a null value. If the
foreign-key does not support null values, a new relationship must be defined,
the foreign-key property must be assigned another non-null value, or the
unrelated object must be deleted.  

修改 以下是调用删除范围的方法:

List<People> peopleToAdd = new List<People>() { person1, person2 };
context.People.RemoveRange(peopleToAdd);
context.SaveChanges();

1 个答案:

答案 0 :(得分:0)

RemoveRanges() 不支持级联删除。您所能做的就是,使用适合您的 foreach 或 for 循环,然后使用 remove()。 例如。在你的情况下,你可以做的是,

foreach(People people in peopleToAdd){
  context.People.Remove(people);
}
context.SaveChanges();