EF Core:急切加载(.include)子类别(自我参考)

编程入门 行业动态 更新时间:2024-10-08 06:23:41
本文介绍了EF Core:急切加载(.include)子类别(自我参考)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我们有这样的东西

var categories = _context.Categories.Include("Categories1.Categories1.Categories1");

该方法可以处理并处理多达4级深度的子​​类别(这已经足够了,但现在谁知道未来)

That works and handles sub-categories up to 4-level deep (which is enough for now but who knows the future)

有更好的方法吗?

更多信息

More info

我们首先使用数据库.类别表包含以下列:

We use database-first. Category table has these columns:

  • 编号
  • ParentCategoryId<-这具有Category.Id的外键
推荐答案

首先,添加数据批注并使属性可读

Firstly, add data annotations and make properties readable

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 }

然后,假设我们有一个类别

then, let's say we have got a category,

var category = context.Categories .Include(x => x.Parent) .Include(x => x.Children) .FirstOrDefault(filter);

然后我们得到它的父母:

then we get its parents with:

var rootCategory = category.Parent?.Parent?.Parent; //up-to 4 levels by your request

通过以下扩展,我们可以轻松获得其级别:

by following extension, we can easily get its level:

///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; } }

更多推荐

EF Core:急切加载(.include)子类别(自我参考)

本文发布于:2023-11-15 06:25:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1591946.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:急切   加载   类别   自我   EF

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!