以下是数据上下文中的实体。我想在删除父区域时删除子区域。
我试过
级联删除。这在移民中无法生存。
以递归方式列出删除区域z时应删除的所有区域,并使用RemoveRange删除列表中的所有项目。它仍然抛出一个例外
错误:
DELETE语句与SAME TABLE REFERENCE约束冲突
如何删除这种简单关系的项目?
public class Zone
{
public int Id { get; set; }
public string Name { get; set; }
public int? ParentId { get; set; }
[ForeignKey("ParentId")]
public virtual Zone ParentZone { get; set; }
}
public class ZoneDbContext : DbContext
{
public ZoneDbContext(DbContextOptions<ZoneDbContext> options) : base(options)
{
}
public DbSet<Zone> Zones { get; set; }
}
答案 0 :(得分:0)
这种方法有效
public void DeleteMyEntity(MyEntity entity)
{
var target = MyEntities
.Include(x => x.Children)
.FirstOrDefault(x => x.Id == entity.Id);
RecursiveDelete(target);
SaveChanges();
}
private void RecursiveDelete(MyEntity parent)
{
if (parent.Children != null)
{
var children = MyEntities
.Include(x => x.Children)
.Where(x => x.ParentId == parent.Id);
foreach (var child in children)
{
RecursiveDelete(child);
}
}
MyEntities.Remove(parent);
}