efcore icon indicating copy to clipboard operation
efcore copied to clipboard

Lazy loading of Related Data with proxies: Query Asynchronously

Open darius-iko opened this issue 4 years ago • 3 comments

I have a DbContext with enabled proxies lazy-loading set up from [https://learn.microsoft.com/en-us/ef/core/querying/related-data/lazy] (https://learn.microsoft.com/en-us/ef/core/querying/related-data/lazy) . In the DbContext, there are PurchaseHeader entity and PurchaseDetail entity. One PurchaseHeader has many PurchaseDetail. When loading PurchaseDetail from PurchaseHeader, how to query PurchaseDetail asynchronously because I can't find ToListAsync() or FirstOrDefaultAsync() ?

e.g code:

var header = await DbContext.PurchaseHeader.FirstOrDefaultAsync(); // This is fine
var details = await header.PurchaseDetails.ToListAsync(); // This is NOT defined
var details2 = await header.PurchaseDetails.AsQueryable().ToListAsync(); // This will be error in runtime

and this:

var header = await DbContext.PurchaseHeader.FirstOrDefaultAsync(); // This is fine
var details = await header.PurchaseDetails.FirstOrDefaultAsync(); // This is NOT defined
var details2 = await header.PurchaseDetails.AsQueryable().FirstOrDefaultAsync(); // This will be error in runtime

Include provider and version information

EF Core version: EF Core 6 Database provider: Microsoft.EntityFrameworkCore.SqlServer Target framework: .NET 6 Operating system: Windows 10 x64 IDE: Visual Studio 2022 17.3.6

darius-iko avatar Oct 12 '22 13:10 darius-iko

Unfortunately, lazy loading of properties is fundamentally incompatible with async I/O; that's one reason why lazy loading is generally discouraged. Consider using eager load (with Include) or explicit loading instead.

roji avatar Oct 12 '22 15:10 roji

Is there any plan in the future to allow async/IO on lazy loading?

darius-iko avatar Oct 13 '22 09:10 darius-iko

@darius-iko Lazy-loading kicks in when a property is accessed. Properties cannot be async.

ajcvickers avatar Oct 13 '22 09:10 ajcvickers