You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

EF Core 8多父级模型级联删除与SuperChild批量查询方案咨询

问题描述

使用.NET Core 8和EF Core 8开发(AutoMapper与当前问题无关),现有实体类如下:

public class MainA {
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }

    public virtual ICollection<ChildA> ChildsA { get; set; }
    public virtual ICollection<ChildB> ChildsB { get; set; }
    public virtual ICollection<ChildC> ChildsC { get; set; }
}

public class ChildA {
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }

    public virtual ICollection<SubChildA> Childs1 { get; set; }
}

public class SubChildA {
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }

    public virtual ICollection<SuperChild> Childs1 { get; set; }
}

public class ChildB {
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }

    public virtual ICollection<SuperChild> Childs1 { get; set; }
}

public class ChildC {
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }

    public virtual ICollection<SuperChild> Childs1 { get; set; }
}

public class SuperChild {
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
}

遇到的问题

  • 使用Owns...配置可实现级联删除,但无法直接查询所有SuperChild数据,必须关联其他表才能查询
  • 采用常规关系配置时,SuperChild会存在多个外键,且无法实现删除MainA时级联删除所有关联SuperChild的需求
  • 尝试过创建中间链接模型(示例如下),但删除MainA时仅会删除链接表数据,SuperChild数据仍会残留:
public class ChildB {
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }

    public virtual ICollection<ChildB_Link_SuperChild> Childs1 { get; set; }
}

public class ChildB_Link_SuperChild
{
    public Guid ChildBId { get; set; }
    public virtual ChildB ChildB { get; set; }

    public Guid SuperChildId { get; set; }
    public virtual SuperChild SuperChild { get; set; }
}

public class ChildB_Link_SuperChildConfiguration : IEntityTypeConfiguration<ChildB_Link_SuperChild>
{
    public void Configure(EntityTypeBuilder<ChildB_Link_SuperChild> builder)
    {
        builder.HasKey(rd => new { rd.ChildBId, rd.SuperChildId });

        builder.HasOne(x => x.ChildB )
            .WithMany(x => x.Childs1)
            .HasForeignKey(x => x.ChildBId)
            .OnDelete(DeleteBehavior.Cascade);
    
        builder.HasOne(x => x.SuperChild)
            .WithOne()
            .HasForeignKey<ChildB_Link_SuperChild>(x => x.SuperChildId)
            .OnDelete(DeleteBehavior.Cascade);
    }
}

当前考虑的方案

计划采用Owns配置结合Concat查询的方式,示例代码如下:

db.Set<MainA>()
    .SelectMany(x =>
        x.ChildsA.SelectMany(y => y.Childs1).SelectMany(z => z.Childs1)
            .Concat(x.ChildsB.SelectMany(y => y.Childs1))
            .Concat(x.ChildsC.SelectMany(y => y.Childs1))
    )
    .ToList();

疑问

  1. 该方案是否为最优解?
  2. 有无其他实现思路?
  3. 该Concat语句能否被EF Core正确翻译且性能良好?

内容的提问来源于stack exchange,提问作者Flo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 21:56:04