简体   繁体   中英

How to load two navigation property in a single statement in order to avoid database round trips(if any)

What i want is to load two navigation property in my class through database context using entity framework...the way I can do it with Include method... And does it incur me two round trips or not to the db...

Note: I dont want to load it with with EF Context's Include method

Currently I'm doing it this way

db.Entry(category).Reference(p => p.Section).Load(); 
db.Entry(category).Collection("SubCategories").Load();

I want to load this in one statement

You can do this in one trip using EF. Try something like this (making some assumptions on your data/object model):

db.Categories
  .Where(x=> x.ID == category.ID)
  .Select(x=> new {
    Category = x,
    Section = db.Sections.FirstOrDefault(y => y.ID == x.SectionID),
    SubCategories = db.Categories.Where(y=> y.ParentCategoryID == x.ID)
  }).FirstOrDefault();

This will give you one object back (in one trip to the database) that has properties hydrated for the Category, Section, and SubCategories.

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