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#