简体   繁体   English

如何在单个语句中加载两个导航属性,以避免数据库往返(如果有)

[英]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... 我想要的是使用实体框架通过数据库上下文在类中加载两个导航属性...我可以使用Include方法来实现的方式...并且是否会导致我两次往返或不往返于数据库...

Note: I dont want to load it with with EF Context's Include method 注意:我不想使用EF Context的Include方法加载它

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. 您可以使用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. 这将使您返回一个对象(一次访问数据库),该对象具有为Category,Section和SubCategories混合的属性。

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

相关问题 实体框架 - 减少到数据库的往返行程 - Entity framework - Reducing round trips to the database 操纵实体框架以消除到数据库的往返 - Manipulating entity framework to eliminate round trips to the database 在数据库的单次往返中执行两个查询 - Performing two queries in a single round trip to the database EF&Web API 2多次往返数据库以填充对象模型 - EF & Web API 2 Multiple Round trips to the database to populate object model 可以在一个控制器动作中进行多次数据库往返 - Is it OK to do many database round trips in one controller action 如何缓存数据集以停止往返数据库的旅程? - How do I cache a dataset to stop round trips to db? 我如何使用表达式 <Func<T> &gt;在linq语句中,如果我的导航属性是单个项目? - How do i use an Expression<Func<T>> in a linq statement if my navigation property is a single item? 我应该如何维护购物车以避免频繁前往服务器? - How should I maintain the cart to avoid frequent trips to the server? 如何使用BindingSource在DataGridView的单列中绑定Navigation Property(二级模型的两个属性)? - How to bind Navigation Property (second level model's two properties) in DataGridView's single column using BindingSource? 如何避免在Entity Framework中加载集合属性 - How to avoid to load collection property in Entity Framework
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM