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.
source share