Is data loading data from a database?

Suppose we have a method like this:

public IEnumerable<T> FirstMethod() { var entities = from t in context.Products where {some conditions} select t; foreach( var entity in entities ) { entity.SomeProperty = {SomeValue}; yield return entity; } } 

where context is the DataContext created by the Linq to SQL constructor.

Does "FirstMethod" load data into memory from the database (due to the foreach loop) or will it delay it until another foreach loop that does not have a "yield return" is found in a different way, like the following

 public void SecondMethod() { foreach( var item in FirstMethod() ) { {Do Something} } } 
+4
source share
3 answers

Last (deferred); FirstMethod - iterator block (due to yield return ); that means you have a chain of iterators. Nothing is read until the final caller begins to repeat the data; then each record is read in turn during the final calling foreach (between which the connection / command is opened).

using , which surrounds foreach (under the hood), ensures that the connection is closed if foreach is left halfway.

If you want to load data earlier, use .ToList() or .ToArray() to store data locally - but note that this violates the composition - that is, the caller can no longer add additional Where , etc. (which they can if it returns raw IQueryable<T> ).


To your question:

 public IEnumerable<T> FirstMethod() { var entities = from t in context.Products where {some conditions} select t; foreach( var entity in entities.AsEnumerable() ) { entity.SomeProperty = {SomeValue}; yield return entity; } } 

Here AsEnumerable is the key; it ends the IQueryable<T> compound chain and uses LINQ-to-Objects for the rest.

+6
source

In short, it does not load until SecondMethod iterates ...

Read more here for more ...

+2
source

Downloading is delayed until the GetEnumerator method is called in essence , and this does not happen until the GetEnumerator IEnumerable <T> method that you return is called.

+1
source

All Articles