数据结构
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));
参考资料:
延迟加载