ef core 级联删除
电脑版发表于:2021/12/22 11:20
和以前的写法有点不同现在没有modelBuilder.Conventions这种用法了,单独开启级联删除的方法也和以前不太一样
以前的写法:
protected override void OnModelCreating(DbModelBuilder modelBuilder) { //删除掉级联删除的规则 modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>(); }
以前单独的控制写法:
protected override void OnModelCreating(DbModelBuilder modelBuilder) { //关闭级联删除 modelBuilder.Entity<Pet>().HasRequired(a => a.userinfo).WithMany(a => a.pets).HasForeignKey(a => a.UserId).WillCascadeOnDelete(false); }
以前使用的是WillCascadeOnDelete方法,而且参数只有true和false,就是是否开启级联查询
.NET CORE中EF级联删除的写法
使用的是OnDelete,而且参数是枚举不止,ture和false
protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Student>().Property(p => p.RowVersion).IsConcurrencyToken(); modelBuilder.Entity<UserParent>().HasMany(a => a.Students).WithOne(a => a.UserParent).HasForeignKey(a => a.MyUserParentId).OnDelete(DeleteBehavior.NoAction); }
DeleteBehavior.NoAction:就是不开启级联删除,会出发外键约束。
DeleteBehavior.Cascade:就是开启级联删除,是默认值
其他还有:DeleteBehavior.SetNull,DeleteBehavior.ClientSetNull,Restrict等