简体   繁体   English

实体框架会对1:1参考相关表执行n + 1个查询吗?

[英]Will Entity Framework perform n+1 queries for 1:1 reference related tables?

If I have this POCO class. 如果我有这个POCO课程。

class MainEntity
{
    public int id  {get;set;}
    public string name {get;set;}
    public virtual Related myRelated {get;set;}
}

related to this class 与这个班有关

class Related 
{
     public int id  {get;set;}
     public string name {get;set;}
}

The entities are related on a 1:1 basis. 实体按1:1关联。

Will the query db.MainEntity.ToList(); 将查询db.MainEntity.ToList(); perform N+1 queries to the DB due to lazy loading, or, once it's 1:1 reference related, will perform just 1 query? 由于延迟加载而对数据库执行N + 1个查询,或者一旦与1:1参考相关,将仅执行1个查询?

When you do your ToList , it will just retrieve the list of all your MainEntity objects with one query. 当您执行ToList ,它将只使用一个查询来检索所有MainEntity对象的列表。 If you have any related entity linked they will not be loaded at all. 如果您链接了任何相关实体,则将根本不会加载它们。

Then, once you navigate to the myMain.Related property, lazy loading will trigger and will create a query to load the values for that related reference object. 然后,一旦导航到myMain.Related属性,便会触发延迟加载,并将创建一个查询以加载该相关参考对象的值。

Now, if you'd like to directly load all data in the reference in one query it's also possible. 现在,如果您想在一个查询中直接加载引用中的所有数据,则也是可能的。 You can use the .Include extension method to do this. 您可以使用.Include扩展方法来执行此操作。 In your example, it would look something like this: 在您的示例中,它看起来像这样:

db.MainEntity.Include(m => m.Related).ToList()

You should also check this page which goes into the details on how you can do lazy / eager loading and what it means in terms of SQL. 您还应该检查此页面该页面详细介绍了如何进行延迟/急切加载及其对SQL的含义。

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

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