简体   繁体   English

在实体框架中执行Include()时?

[英]When Include() executing in Entity Framework?

I have a simple question but didn't find an answers. 我有一个简单的问题,但没有找到答案。
If I do so 如果我这样做

var result = _db.Table.Include(t => t.Child).Where(t => t.Id == id).Single();

when join is calling? join什么时候打电话? After it found my entity or it includes every child during SQL looking for the row? 在找到我的实体之后,或者它包括SQL期间的每个孩子都在寻找行?
Lets see at the example based on simple db model: 让我们看一下基于简单数据库模型的示例:

public class Head
{
    //... columns
    public virtual Child {get; set;}
    public Guid? ChildId {get; set;}
}
void main()
{
    //The first version of code
    var child = _db.Head.Include(h => h.Child)
        .FirstOrDefault(//boring staff but we don't need child here)
        ?.Child;
    if (child != null)
        foo(child);
    //The second one
    var head = _db.Head.FirstOrDefault(//boring staff);
    if (head != null && head.ChildId.HasValue)
        foo(head.Child); // I know here we make a new request to our db
}

Which of two options are more productive? 两种选择中哪个更有效? I'm worry about "extra childs loading by SQL" when I need only one object based on filters query of parent table. 当我仅需要基于父表的过滤器查询的一个对象时,我担心“通过SQL加载额外的子对象”。
Thanks in advance! 提前致谢!

It will evaluate the where condition first. 它将首先评估条件。 Not in C# but in SQL which gets generated. 不是在C#中,而是在生成的SQL中。 This will generate a SQL something like 这将生成类似

SELECT top 1 .... FROM Table t
JOIN Child c ....
WHERE t.Id = id

Your database server will create a execution plan which will look for the item in the index and get corresponding child. 您的数据库服务器将创建一个执行计划,该计划将在索引中查找项目并获得相应的子项。

Without Include the loading of Child objects is deferred until you need them. 如果没有Include则将延迟加载Child对象,直到需要它们为止。 Hence, if you were to iterate parent/child groups like this 因此,如果您要像这样迭代父/子组

foreach (var parent in _db.Table.Include(t => t.Child).Where(p => p.Name.StartsWith("Q")))
    foreach (var child in parent.Child)
        Console.WriteLine($"{child}, child of {parent}");

the number of round-trips would be equal to the number of parents plus one. 往返次数等于父母人数加一。

If you use Include , all Child objects are loaded along with the parent object, without making a separate round-trip for each parent. 如果使用Include ,则将所有Child对象与父对象一起加载,而无需为每个父对象进行单独的往返。 Hence, the number of database round-trips for the above code would be equal to 1. 因此,以上代码的数据库往返次数将等于1。

In a case with Single , which could be rewritten as follows Single的情况下,可以如下重写

var result = _db.Table.Include(t => t.Child).Single(t => t.Id == id);

the number of round-trips would be 1 with Include and 2 without Include . 往返次数将为1( Include和2(不Include

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

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