class OrgUnit
{
public int Id { get; set; }
public string Name { get; set; }
public OrgUnit Parent { get; set; }
public List<OrgUnit> Children { get; set; }
}
class OrgUnitConfig : IEntityTypeConfiguration<OrgUnit>
{
public void Configure(EntityTypeBuilder<OrgUnit> builder)
{
builder.ToTable("OrgUnit");
builder.Property(e => e.Name).HasMaxLength(50).IsRequired();
builder.HasOne(o => o.Parent).WithMany(p => p.Children);
}
}
private static Task ReadOrgUnit(MyDbContext ctx)
{
// 使用include()取出root,可以带出直接的children(asia, america),但是无法带出asia的children。
//ctx.OrgUnits.Include(o => o.Children).FirstOrDefault(o => o.Parent == null);
// 反而取出所有的orgunit以后,EF会自动建立连接。
OrgUnit[] units = ctx.OrgUnits.Where(_ => true).ToArray();
PrintOrgUnit(units.FirstOrDefault(u => u.Parent == null), 0);
return Task.CompletedTask;
}
private static void PrintOrgUnit(OrgUnit orgUnit, int indent)
{
if (orgUnit == null)
return;
Console.WriteLine(new string(' ', indent) + orgUnit.Name);
if (orgUnit.Children == null)
return;
foreach (OrgUnit child in orgUnit.Children)
{
PrintOrgUnit(child, indent + 2);
}
}
private static async Task SaveOrgUnits(MyDbContext ctx)
{
OrgUnit root = new OrgUnit { Name = "root" };
OrgUnit asia = new OrgUnit { Name = "asia", Parent = root };
OrgUnit china = new OrgUnit { Name = "china", Parent = asia };
OrgUnit sg = new OrgUnit { Name = "singapore", Parent = asia };
OrgUnit america = new OrgUnit { Name = "america", Parent = root };
OrgUnit usa = new OrgUnit { Name = "usa", Parent = america };
OrgUnit can = new OrgUnit { Name = "canada", Parent = america };
ctx.OrgUnits.AddRange(new OrgUnit[] { root, asia, china, sg, america, usa, can });
await ctx.SaveChangesAsync();
}