Entity Framework - Lazy Loading even works with ToList ()

First of all, I am using EF 6.0 using the Code First approach. My context configuration is set to Enable Proxy Creation and Lazy Loading.

My question is: Should lazy loading work with the results of a method that returns IEnumerable (and not IQueryable)?

I think the code below explains:

public void Test() { var company = GetCompanies().FirstOrDefault(); if (company.Employees.Count() > 0) { //I got here without errors! } } public IEnumerable<Company> GetCompanies() { var company = context.Companies.ToList(); //Note that I did not Include the Employee (child table) return company; } 

Mark this comment, which I say: "I am here without errors!". This means that lazy loading works even after calling ToList (). I thought that after converting IQueryable to List or IEnumerable EF would lose the ability to do lazy loading.

I noticed that the proxy is still enabled for objects returned by the GetCompanies method (in debbug mode I see this ugly hash, for example: System.Data.Entity.DynamicProxies.Company_7035BEA374959AC1 ...).

Lazy loading works, even calling it in different DLLs. It's right? I mean, can another DLL make subsequent calls to my database, even if my method returns IEnumerable (and not IQueriable)?

Any clarification would be greatly appreciated.

+7
c # entity-framework
source share
1 answer

Mark this comment, which I say: "I am here without errors!". That means this lazy loading works even after calling ToList ().

What the whole point of lazy loading is: you can get objects from the database when they are needed (i.e. when you get access to the property), and not just the first time you run the request (i.e. your .ToList() call) .

Lazy loading works, even calling it in different DLLs. Is it true? I mean, can another DLL make subsequent calls to my database, even if my method returns IEnumerable (and not IQueriable)?

Yes, this is correct, but be careful if you manage your context, lazy loading will not work (it will throw an ObjectDisposedException ). In addition, although your code will work, you may experience performance issues due to the number of SQL queries generated.

Side note: I personally recommend not using lazy loading. See https://stackoverflow.com>

+4
source share

All Articles