user3818229
user3818229

Reputation: 1647

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? After it found my entity or it includes every child during SQL looking for the row?
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.
Thanks in advance!

Upvotes: 0

Views: 75

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727077

Without Include the loading of Child objects is deferred until you need them. 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. Hence, the number of database round-trips for the above code would be equal to 1.

In a case with Single, which could be rewritten as follows

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.

Upvotes: 1

Vijay
Vijay

Reputation: 543

It will evaluate the where condition first. Not in C# but in SQL which gets generated. 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.

Upvotes: 1

Related Questions