我有两个实体人和FollowUps有一个一对多的关系,与级联删除。如此处所定义的(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. 编辑:是如何调用remove范围的:
List<People> peopleToAdd = new List<People>() { person1, person2 };
context.People.RemoveRange(peopleToAdd);
context.SaveChanges();发布于 2021-03-08 11:11:52
RemoveRanges()不支持级联删除。您所能做的就是,只需使用foreach或for循环任何适合您的方法,只需使用remove()即可。就像。就你而言你能做的就是,
foreach(People people in peopleToAdd){
context.People.Remove(people);
}
context.SaveChanges();https://stackoverflow.com/questions/40652566
复制相似问题