简体   繁体   English

如何避免使用C#和Entity Framework进行递归对象获取

[英]How do I avoid recursive object fetching with C# and Entity Framework

Right now, for accessing all child categories of a self joining object I am making query like this. 现在,为了访问自连接对象的所有子类别,我正在这样查询。

var productCategories = db.Categories.Inlcude("ChildCategories")
            .Inlcude("ChildCategories.ChildCategories")
            .Inlcude("ChildCategories.ChildCategories.ChildCategories")
            .Inlcude("ChildCategories.ChildCategories.ChildCategories.ChildCategories")
            .Inlcude("ChildCategories.ChildCategories.ChildCategories.ChildCategories.ChildCategories")
            .Inlcude("ChildCategories.ChildCategories.ChildCategories.ChildCategories.ChildCategories.ChildCategories")

What can be done to about this kind of query? 这种查询可以做什么?

To allow the IQueryable to fetch everything (opposite of Lazy Loading), you can disable Lazy Loading on the DBContext. 要允许IQueryable提取所有内容(与延迟加载相反),可以在DBContext上禁用延迟加载。

 using(DBContext db = new DBContext) {
      db.ContextOptions.LaxyLoadingEnabled = false;
      // TODO: Other code here
 }

Edit: Fixed answer in response to @Slauma comment. 编辑:修复了对@Slauma评论的答复。

In the case that ChildCategory is a child class of Category (inheritance): 如果ChildCategory是Category(继承)的子类:

If you want the IQueryable to fetch everything for a ChildCategory , you can use the OfType<T>() method. 如果希望IQueryable提取ChildCategory所有内容,则可以使用ChildCategory OfType<T>()方法。

 var productCategories = db.Categories.OfType<ChildCategories>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用实体框架C#创建和插入一对多对象 - How do I create and insert one-to-many object with entity framework c# 如何在 C# 中将递归对象转换为集合? - How do I convert a recursive object to a Collection in C#? C#实体框架递归层次结构查询 - C# Entity Framework recursive hierarchy query 如何将实体对象传递给C#中的函数 - How do I pass an Entity Object to a function in C# C# 实体框架:如何结合 a.Find 和.Include 在 Model Object 上? - C# Entity-Framework: How can I combine a .Find and .Include on a Model Object? 匿名对象如何工作C#实体框架 - How to anonymous object works c# entity framework 如何在 C# 实体框架核心中使用 class 的构造函数,并将 class 作为字段? - How do I use constructer for a class with a class as a field in C# Entity Framework Core? 如何在 C# 实体框架中获取 SQL 查询的结果? - How do I get the result of SQL Query in C# Entity Framework? 如何使用实体框架代码优先将 Boolean 数组绑定到 C# model? - How do I bind a Boolean array to a C# model using Entity Framework Code First? 如何使用 Entity Framework Core 添加/更新 C# 中的孩子的孩子? - How do I add/update the child of a child in C# using Entity Framework Core?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM