Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FirstorDefault() causes lazy loading or eager loading for linq to sql

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

For e.g

  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

like image 308
JulyOrdinary Avatar asked May 31 '13 14:05

JulyOrdinary


People also ask

Is FirstOrDefault lazy loading?

FirstOrDefault(); This is called “eager loading”, you are basically loading everything you need at once.

What is the use of FirstOrDefault in LINQ?

FirstOrDefault<TSource>(IEnumerable<TSource>, TSource)Returns the first element of a sequence, or a specified default value if the sequence contains no elements.

What is lazy loading and eager loading in LINQ?

While lazy loading delays the initialization of a resource, eager loading initializes or loads a resource as soon as the code is executed. Eager loading also involves pre-loading related entities referenced by a resource.

What is the difference between first () and FirstOrDefault () Select method in LINQ?

The major difference between First() and FirstOrDefault() is First will throw an exception when there are no results and FirstOrDefault won't. In fact, FirstOrDefault will simply return the null value (reference types) or the default value of the value type.


1 Answers

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

It eagerly computes the result of the query. The easiest way to reckon about this is to realize that the return type is int, not IEnumerable<int> which can be deferred until GetEnumerator is called, but int has no such mechanism.

The phrasing of your question suggests that you're also asking if there is a way to change this behavior. There is, but not directly through FirstOrDefault or any mechanisms within LINQ. But you can defer using Lazy<T>. No compiler handy, so forgive me if this doesn't compile but it should get you 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
    //
}
like image 114
jason Avatar answered Oct 27 '22 01:10

jason