繁体   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