Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework - Lazy Loading working even with ToList()

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

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

I think the code below is more explanatory:

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;              
}

Note comment where I say that: "I got here without errors!". It means that lazy loading is working even after ToList() call. I thought that after converting IQueryable to List or IEnumerable the EF would lose the capability of doing lazy loading.

I have noted that the Proxy still enabled for the entities that are returned by GetCompanies method (in debbug mode I can see that ugly hash like: System.Data.Entity.DynamicProxies.Company_7035BEA374959AC1...).

The lazy loading works even when calling it on different DLL. Is this correct? I mean, can a different DLL make subsequent calls in my database even if my method returns an IEnumerable (and not IQueryable)?

Any clarification will be greatly appreciated.

like image 256
fabriciorissetto Avatar asked Mar 07 '14 12:03

fabriciorissetto


1 Answers

Note that comment that I say: "I got here without errors!". It means that lazy loading is working even after ToList() call.

That's the whole point of lazy-loading: you can get entities from the DB when they are required (i.e. when you access to the property), not only when you execute the query for the first time (i.e. your call to .ToList()).

The lazy loading works even calling it on different DLL. Is this correct? I mean, can a different DLL made subsequent calls in my database even if my method return an IEnumerable (and not IQueriable)?

Yes it's correct, but be careful, if you dispose your context, lazy loading won't work (it'll throw an ObjectDisposedException). Also, while your code will work, you might have performance issues because of the number of SQL requests generated.

Side note: personally I recommend to not use lazy-loading. See https://stackoverflow.com/a/21379510/870604

like image 132
ken2k Avatar answered Oct 19 '22 07:10

ken2k