• 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();
            }
    
  • 相关阅读:
    软件过程管理读书笔记02
    交叉验证
    oracle两张表数据匹配,Oracle-left join两表关联只取B表匹配到的第一条记录
    oracle批量新增
    oracle聚合函数XMLAGG用法简介
    form表单导致url连接重定向问题处理
    请求200,返回没内容,360可以看到response内容(待看),nginx返回内容被截取
    jsonp请求返回前面带有个null
    oracle日期转换的一些坑
    Java中将List<String>转化为以,分割的字符串或相反(转载)
  • 原文地址:https://www.cnblogs.com/mryux/p/15856878.html
Copyright © 2020-2023  润新知