繁体   English   中英

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

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

现在,为了访问自连接对象的所有子类别,我正在这样查询。

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")

这种查询可以做什么?

要允许IQueryable提取所有内容(与延迟加载相反),可以在DBContext上禁用延迟加载。

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

编辑:修复了对@Slauma评论的答复。

如果ChildCategory是Category(继承)的子类:

如果希望IQueryable提取ChildCategory所有内容,则可以使用ChildCategory OfType<T>()方法。

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

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM