25

I have a question about Entity Framework Core and using LINQ. I would like to get the other table details while accessing the Clients table. I can get them using below code. There are a total of around 10 tables I need to join, in this case is the below approach is good or any other, better approach? ClientId is the foreign key for all tables.

Actually I am getting a warning as below

[09:34:33 Warning] Microsoft.EntityFrameworkCore.Query Compiling a query which loads related collections for more than one collection navigation either via 'Include' or through projection but no 'QuerySplittingBehavior' has been configured. By default Entity Framework will use 'QuerySplittingBehavior.SingleQuery' which can potentially result in slow query performance. See https://go.microsoft.com/fwlink/?linkid=2134277 for more information. To identify the query that's triggering this warning call 'ConfigureWarnings(w => w.Throw(RelationalEventId.MultipleCollectionIncludeWarning))'

Code:

var client = await _context.Clients
                .Include(x => x.Address)
                .Include(x => x.Properties)
                .Include(x => x.ClientDetails)
                -------------------
                -------------------
                -------------------
                -------------------
                .Where(x => x.Enabled == activeOnly && x.Id == Id).FirstOrDefaultAsync();
5
  • The first step to optimising the query is probably to work out how you would best accomplish the same result in SQL. You can then fashion your LINQ to Entities code to best match that. Commented Apr 27, 2021 at 1:44
  • 1
    Just add AsSplitQuery(). Loading such data without this operator is wasting resources. Warning is totally correct. Answered similar question. about performance issues stackoverflow.com/a/67243921/10646316 Commented Apr 27, 2021 at 5:15
  • 2
    What is "better"? We don't know the purpose of this query. Commented Apr 27, 2021 at 7:48
  • The best part about this is that if you configure it to always use one or the other, it'll still give the warning. Commented Feb 3, 2022 at 18:06
  • @CaptainPrinny really? -_- I wonder if you can log the query without throwing. I don't want an actual exception. I'm justcurious. Commented Mar 22, 2023 at 18:57

2 Answers 2

23

Actually when you use Eager loading (using include()) It uses left join (all needed queries in one query) to fetch data. Its default the ef behavior in ef 5. You can set AsSplitQuery() in your query for split all includes in separated queries. like:

var client = await _context.Clients
            .Include(x => x.Address)
            .Include(x => x.Properties)
            .Include(x => x.ClientDetails)
            -------------------
            -------------------
            -------------------
            -------------------
            .Where(x =>x.Id == Id).AsSplitQuery().FirstOrDefaultAsync()

This approach needs more database connection, but it's nothing really important. and for the final recommendation, I advise using AsNoTracking() for queries to high performance.

1
  • 2
    I believe without AsSplitQuery() AsNoTrackingWithIdentityResolution() is needed otherwise it will map the same entity multiple times, I don't know if it's the same when using AsSplitQuery() instead.
    – Xriuk
    Commented Oct 5, 2022 at 7:02
2

I have 3 different approaches depending on the version of EF Core you're using

EF Core 5 - as some have mentioned in previous answers there is new call which will simply break up the query into smaller subqueries and map all the relations in the end.

/*rest of the query here*/.AsSplitQuery();

If you are not able to just migrate your EF version you could still split the query manually

var client = await _context.Clients.FirstOrDefaultAsync(t => t.Enabled /*other conditions*/);

var Address = await _context.Addresses.FirstOrDefaultAsync(t => t.ClientId == client.Id);

/// Because they are tracked EF's entitytracker can under the hood 
/// map the sub queries to their correct relations 
/// in this case you should not use .AsNoTracking() 
/// unless you would want to stitch relations together yourself

Another alternative is to write your query as a Select statement. This greatly improves performance but is a bit more of a hassle to construct.

var clientResult = await _context.Clients.Where(x => x.Id == id).Select(x => new 
{
 client = x, 
 x.Address,
 Properties = x.Properties.Select(property => new 
                    { 
                        property.Name /*sub query for one to many related*/ 
                    }).ToList(), 
 x.ClientDetails
}).ToListAsync();

it doesn't take many includes to create cartesian explosion
you can read more up on the problem at hand in this article here cartesian explosion in EF Core

and referral link to optimizing performance through EF Core can be found here Maximizing Entity Framework Core Query Performance

7
  • Select variant makes cartesian explosion believe me. And there is no option to use AsSplitQuery with custom projection right now. Commented Apr 27, 2021 at 18:17
  • Hi Svyatoslav. I didn't state that select didn't result in cartesian explosion, but will under the hood perform better than .include. But yes any sort of join be it cross, left, outer left joins will give cartesian explosion if done in a bad way. But different scenarios might require different solutions Commented Apr 28, 2021 at 6:17
  • In EF any select to other table in projection is cartesian explosion, except First, FirstOrDefault, etc. Commented Apr 28, 2021 at 6:22
  • I'm sorry but I don't follow that comment. First or default can be used within a select statement. and select doesn't select to a table, but selects from a table. Commented Apr 28, 2021 at 6:28
  • 2
    Actually AsSplitQuery is result of community vote. EF team has made breaking change from EF Core 2.x - removed query splitting which was default behaviour. Commented Apr 29, 2021 at 9:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.