entity-framework - EF Core:急切加载 (.Include) 子类别(自引用)
问题描述
我们有这样的东西
var categories = _context.Categories.Include("Categories1.Categories1.Categories1");
这可以工作并处理高达 4 级深度的子类别(现在就足够了,但谁知道未来)
有更好的方法吗?
更多信息
我们使用数据库优先。类别表具有以下列:
- ID
- ParentCategoryId <-- 这具有 Category.Id 的外键
解决方案
首先,添加数据注释并使属性可读
public partial class Category
{
public Category()
{
this.Children = new HashSet<Category>();
}
[Key]
public int Id { get; set; }
public string WhatEverProperties { get; set; }
public int ParentCategoryId { get; set; }
[ForeignKey("ParentCategoryId")]
[InverseProperty("Category")]
public Category Parent { get; set; } // name "Category1" as "Parent"
[InverseProperty("Category")]
public ICollection<Category> Children { get; set; } // Name it as Children
}
那么,假设我们有一个类别,
var category = context.Categories
.Include(x => x.Parent)
.Include(x => x.Children)
.FirstOrDefault(filter);
然后我们得到它的父母:
var rootCategory = category.Parent?.Parent?.Parent; //up-to 4 levels by your request
通过以下扩展,我们可以很容易地得到它的等级:
///this extension works only if you used `.Include(x => x.Parent)` from query
public static class CategoryExtensions
{
public static int Level(this Category category)
{
if (category.Parent == null)
{
return 0;
}
return category.Parent.Level() + 1;
}
}
推荐阅读
- javascript - React/JavaScript - 验证两个或更多输入
- linux - 在 Aws Elastic Beanstalk 上增加 client_max_body_size
- angular - 如何从列表组件中显示详细组件的数据?
- c# - 为什么 IdentityServer persistedgrants 中没有更新刷新令牌到期?
- java - 当我尝试实现 RecycleView 时出错
- c# - 当我尝试将 C# 中的文件移动到第一个文件夹上带有侦听器的另一个文件夹时出错
- jquery - 如何检查一个元素是否在 ejs 模板中具有类 d-none?
- java - onActivityResult 不能与 onBackPressed 一起使用?
- php - 嗨,我正在尝试更改 functions.php 上的这些文本,但我不能,只有第一个文本更改,但第二个“Detalles de facturación”保持不变
- c - 如何在不使用 qsort 的情况下在 C 中实现后缀数组?