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);

或者git

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

參考資料:
延遲加載github

示例代碼

示例代碼c#

相關文章
相關標籤/搜索