FirstorDefault () causes lazy loading or loading for linq on sql

What is the default behavior of FirstOrDefault () when used with Linq to SQL?

For instance,

int value = (from p in context.tableX select p.Id).FirstOrDefault() // Value will initialized here or if(value > 0) // query will be executed here???? { //do something } 

thanks

+6
source share
4 answers

What is the default behavior of FirstOrDefault () when used with Linq to SQL?

He readily calculates the result of the query. The easiest way to find out about this is to understand that the return type is int , not IEnumerable<int> , which can be deferred until GetEnumerator is called, but int has no such mechanism.

The wording of your question assumes that you are also asking if there is a way to change this behavior. LINQ exists, but not directly, through FirstOrDefault or any mechanisms. But you can delay using Lazy<T> . There is no compiler, so goodbye if this does not compile, but it should be very close.

 Lazy<int> value = new Lazy<int>( () => { var query = from p in context.tableX select p.Id; var result = query.FirstOrDefault(); return result; } ); if(value.Value > 0) { // execution will be deferred until here // } 
+10
source

All standard Linq statements that return a single, non-enumerable result are executed immediately at the point where the request is made. Thus, FirstOrDefault , Count , Sum and other statements that return the same value are executed immediately.

Here is a good MSDN article Classification of Standard Query Operators by Runtime Method

+8
source

Lively download!

If you think about it, it just returns a simple int - int cannot represent a "way to go and get int ". (What for Lazy<int> for ...)

+2
source

It becomes a downloadable load when you use extension methods for an enumerated result. If you do not use these extension methods, it will be a Lazy download, and you will not be able to get the values ​​until you list the linq result

+2
source

Source: https://habr.com/ru/post/946274/


All Articles