• dotnetcore EF 使用自引用实体


        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();
            }
    
  • 相关阅读:
    剑指 Offer 03. 数组中重复的数字
    Leetcode_80: removeDuplicates
    Leetcode_27: removeElement
    Leetcode_26: removeDuplicates
    Leetcode-283: moveZeroes
    Module build failed: Error: Cannot find module 'node-sass’解决
    js实现简单的计算器
    根据经纬度显示地图、地图缩小偏移处理
    js实现滑动到屏幕底部
    【基础】在网页中嵌入页面
  • 原文地址:https://www.cnblogs.com/mryux/p/15856878.html
Copyright © 2020-2023  润新知