简体   繁体   中英

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.

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

Edit: Fixed answer in response to @Slauma comment.

In the case that ChildCategory is a child class of Category (inheritance):

If you want the IQueryable to fetch everything for a ChildCategory , you can use the OfType<T>() method.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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