Efcore: How to use Lazy loading without Include?

Created on 3 Sep 2020  ·  4Comments  ·  Source: dotnet/efcore

Our team update the project from EF6 to EF Core 5.0,

In the past,we use the navigation properties without “include”
Like:
var deptName=_db.Users .Select(m=>new { m.userName, **DeptName=m.Department.Name** })

Now,I must add 'include',

var deptName=_db.Users .Include(u=>u.Department) .Select(m=>new { m.userName, **DeptName=m.Department.Name** })

If I didn't add include,the department was null,and throw exception.

I hope use Lazy loading without Include,because so many code without include.

We use Microsoft.EntityFrameworkCore.Proxies
optionsBuilder.**UseLazyLoadingProxies()** .ConfigureWarnings(warnings => warnings.Ignore(CoreEventId.DetachedLazyLoadingWarning)) .UseSqlServer(connection, op => { op.CommandTimeout((int)TimeSpan.FromMinutes(5).TotalSeconds); })

EF Core version: 5.0-Preview8
Database provider: Microsoft.EntityFrameworkCore.SqlServer
Target framework: .NET Core 3.1
Operating system: WIndows Server 08 R2
IDE: Visual Studio 2019

closed-question customer-reported

All 4 comments

You don't need include for that. Can you share a small runnable repro code which shows exception?

You don't need include for that. Can you share a small runnable repro code which shows exception?

image

When I used firstordefault() or AsEnumrable() , It will throw exception

That is different from query you posted in first post. In first post you are using custom projection, there is no entity type being projected out so include is not needed. If you are projecting out entity then you would need include or lazy loading

Refer to our documentation on lazy loading.

That is different from query you posted in first post. In first post you are using custom projection, there is no entity type being projected out so include is not needed. If you are projecting out entity then you would need include or lazy loading

Refer to our documentation on lazy loading.

Thanks,I will check my code

Was this page helpful?
0 / 5 - 0 ratings