数据结构
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));
参考资料:
延迟加载
示例代码
原文地址:https://www.cnblogs.com/luomingui/p/11964990.html
时间: 2024-10-11 07:11:08