Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which methods use in Linq to force a retrieving data from database

When i use this query, i don't retrieve data from database:

var query = db.Table.Where(x => x.id_category.HasValue).Select(x => x.Id);


But if i use this, i'll retrieve data:

var dataRetrieved = query.ToList();  

Which others methods, like ToList(), i can force a retrieving data?

like image 956
Daniel Moreira Avatar asked Feb 11 '23 07:02

Daniel Moreira


2 Answers

LINQ works by building up a series of query commands, and waits until the last possible moment to execute them. In order to force execution, you have to ask the query for "real" data, not just a description of the steps to get it.

According to this MSDN article (emphasis mine):

LINQ queries are always executed when the query variable is iterated over, not when the query variable is created....

To force immediate execution of a query that does not produce a singleton value, you can call the ToList method, the ToDictionary method, or the ToArray method on a query or query variable....

You could also force execution by putting the foreach or For Each loop immediately after the query expression, but by calling ToList or ToArray you cache all the data in a single collection object.

like image 162
BJ Myers Avatar answered Feb 13 '23 02:02

BJ Myers


The select returns an IEnumerable, which is a sequence of values to invoke a transform function on. So it depends on you what transformation you want? you want list or array? you can also traverse through and manipulate each piece independently using a foreach loop. Following page will give you an idea of what you can do with your values.

like image 41
Ebad Masood Avatar answered Feb 13 '23 04:02

Ebad Masood