簡體   English   中英

如何在單個語句中加載兩個導航屬性,以避免數據庫往返(如果有)

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

我想要的是使用實體框架通過數據庫上下文在類中加載兩個導航屬性...我可以使用Include方法來實現的方式...並且是否會導致我兩次往返或不往返於數據庫...

注意:我不想使用EF Context的Include方法加載它

目前我正在這樣做

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

我想在一個語句中加載

您可以使用EF進行一次旅行。 嘗試這樣的事情(對數據/對象模型做一些假設):

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();

這將使您返回一個對象(一次訪問數據庫),該對象具有為Category,Section和SubCategories混合的屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM