简体   繁体   中英

Include() vs Select() performance

I have a parent entity with a navigation property to a child entity. The parent entity may not be removed as long as there are associated records in the child entity. The child entity can contain hundreds of thousands of records.

I'm wondering what will be the most efficient to do in Entity Framework to do this:

var parentRecord = _context.Where(x => x.Id == request.Id)
                           .Include(x => x.ChildTable)
                           .FirstOrDefault();

// check if parentRecord exists

if (parentRecord.ChildTable.Any()) {
  // cannot remove
}

or

var parentRecord = _context.Where(x => x.Id == request.Id)
                            .Select(x => new {
                                  ParentRecord = x,
                                  HasChildRecords = x.ChildTable.Any()
                            })
                           .FirstOrDefault();

// check if parentRecord exists

if (parentRecord.HasChildRecords) {
  // cannot remove
}

The first query may include thousands of records while the second query will not, however, the second one is more complex.

Which is the best way to do this?

I would say it depens. It depends on which DBMS you're using. it depends on how good the optimizer works etc. So one single statement with a JOIN could be far faster than a lot of SELECT statements.

In general I would say when you need the rows from your Child table use .Include() . Otherwise don't include them. Or in simple words, just read the data you need.

The answer depends on your database design. Which columns are indexed? How much data is in table?

Include() offloads work to your C# layer, but means a more simple query. It's probably the better choice here but you should consider extracting the SQL that is generated by entity framework and running each through an optimisation check.

You can output the sql generated by entity framework to your visual studio console as note here .

This example might create a better sql query that suites your needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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