简体   繁体   中英

Which is the better way to load a single entity with its related data with EF Core in ASP.NET Core?

Just by curiosity, performance wise in EF Core, which is the better way to load a single entity with its related data?

Eager loading?

Customer customer = await _efContext.Customers
    .Include(c => c.ManyContacts)
    .Include(c => c.ManyOrders)
    .SingleAsync(c => c.CustomerId == customerId);

Explicit loading?

 Customer customer = await _efContext.Customers.FindAsync(customerId);
 await _efContext.Entry(customer).Collection(c => c.ManyContacts).LoadAsync();
 await _efContext.Entry(customer).Collection(c => c.ManyoOrders).LoadAsync();

Or is there an even better way to do it?

If you have EF Core 5 you can always use eager loading in these cases.

This version always loads everything in one single query, except you say .AsSplitQuery() . Then every table is loaded in a separate query.

But there is no better way. It depends on your situation.

Eager/lazy is not relevant here, since it's still you who decides the exact time when the requests will be done. Three requests will always be longer than one, so the question is, how often the linked arrays are needed. If they are needed every time, there is definitely no point in splitting the requests. If not... Well, you need to profile it yourself then.

But the performance should not be your main concern. To load everything in one request is simpler and easier to understand. So I would suggest to always go with the simpler solution, even if it's not the best performance-wise. And to start tweaking and optimizing only if it turns out that the performance is too low, and only if the profiling shows that the bad SQL is the reason for that. Spoiler: it probably won't.

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