Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a LINQ lazy loading problem?

Tags:

linq

Something very strange is happening in my program:

I make this query agt.DefaultNr == 1 on a collection and get 3 items as Result:

IEnumerable<Agent> favAgents =
            from agt in builtAgents where agt.DefaultNr == 1 select agt;

For every item I set the DefaultNr = 0

foreach (Agent noFavAgt in favAgents)
{
    noFavAgt.DefaultNr = 0;
}

I do another query but for some reason my favAgents collection is empty now!

IEnumerable<Agent> smallAgents = (from agt in favAgents
    where agt.tempResultCount < 30
    orderby agt.tempResultCount descending
    select agt);

What is going on here?

Is this a LINQ lazy loading problem?

Looks like there will be some kind of re-query after I set all items = 0 because I my collection is empty!

like image 225
TalkingCode Avatar asked Jul 19 '10 15:07

TalkingCode


People also ask

Is LINQ lazy loading?

What is Lazy Loading? Lazy Loading means the related entities are not loaded, until we iterate through them or bind them the data. By default, LINQ to SQL loads the related entities, using Lazy Loading. There is one-to-many relationship between Department and Employees entities.

How do I know if Lazyload is working?

If you're not sure if lazy loading is working correctly, you can open the Chrome DevTools and check that the images are not loaded until the scroll. Here are the steps you should take: Open the Chrome DevTools, go to the Network tab and the Img filter. At this point, reload the page.

Is IQueryable lazy loading?

Both IQueryable and IEnumerable support lazy loading of data from remote database servers.

Which is better lazy loading or eager loading?

Use Eager Loading when you are sure that you will be using related entities with the main entity everywhere. Use Lazy Loading when you are using one-to-many collections. Use Lazy Loading when you are sure that you are not using related entities instantly.


1 Answers

This is not lazy loading, it's deferred execution. When you define your initial enumerable, you're defining a query, not a collection. You're correct that it's performing a requery; every time you iterate over favAgents, it will execute the query that you defined. If you want to create a list based off of that query that doesn't change, add ToList().

var favAgents = 
    (from agt in builtAgents where agt.DefaultNr == 1 select agt).ToList();

Doing this will create a list in memory and cache the results of the query at that point in time.

like image 56
Adam Robinson Avatar answered Oct 21 '22 09:10

Adam Robinson