• EntityFrameworkCore 单表树状结构配置


    数据结构

    public class TreeNode
    {
        [Key]
        public long Id { get; set; }
        public string NodeName { get; set; }
        public long? ParentId { get; set; }
        public virtual TreeNode Parent { get; set; }
        public virtual ICollection<TreeNode> Children { get; set; }
    
    }
    

    配置

    //单表树状结构
    modelBuilder.Entity<TreeNode>()
        //主语this,拥有Children
        .HasMany(x => x.Children)
        //主语Children,每个Child拥有一个Parent
        .WithOne(x => x.Parent)
        //主语Children,每个Child的外键是ParentId
        .HasForeignKey(x => x.ParentId)
        //这里必须是非强制关联,否则报错:Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
        .OnDelete(DeleteBehavior.ClientSetNull);
    

    数据查询需要使用延迟加载

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseLazyLoadingProxies()
            .UseSqlServer(myConnectionString);
    

    或者

        .AddDbContext<BloggingContext>(
            b => b.UseLazyLoadingProxies()
                  .UseSqlServer(myConnectionString));
    

    参考资料:
    延迟加载

    示例代码

    示例代码

  • 相关阅读:
    SQL行列转换
    ASP.NET 〈%# 〉与〈%=〉的区别
    超级强大的 分页Sql存储过程
    ASP.Net 路径问题
    sql server分页
    JavaScript Rules2
    JavaScript Rules
    Draggable
    PHP面向对象编程静态变量(类变量)
    PHP 面向对象成员方法
  • 原文地址:https://www.cnblogs.com/Lulus/p/9497878.html
Copyright © 2020-2023  润新知