Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Dapper's IEnumerable<T> have deferred or immediate execution?

When I execute a query in Dapper and only want to retrieve a block of records, can I use .Skip().Take(), or do I need use select top n * in the SQL?

eg Given a table with 10,000 records and I only want the first 200 because my list page only shows 200 per page. Do I run this?

conn.Query<Widget>("select * from Widgets").Skip((page - 1) * size).Take(size);

Or this:

conn.Query<Widget>("select top 200 * from Widgets");

Is Dapper's .Query<T> method deferred or not?

like image 936
JK. Avatar asked Oct 19 '13 00:10

JK.


People also ask

Does IEnumerable support deferred execution?

You can implement deferred execution for your custom extension methods for IEnumerable using the yield keyword of C#. For example, you can implement custom extension method GetTeenAgerStudents for IEnumerable that returns a list of all students who are teenagers.

What is deferred and immediate execution in LINQ?

In Deferred Execution, the query is not executed when declared. It is executed when the query object is iterated over a loop. In Immediate Execution, the query is executed when it is declared.

Is IQueryable deferred?

There are two types of IQueryable extension methods: Deferred Methods: The query expression is modified but the query is not resolved (Select, Where, etc.). Immediate Methods: The query expression is modified and the query is resolved (Count, First, etc.).

What is deferred execution in LINQ C#?

LINQ queries are always executed when the query variable is iterated over, not when the query variable is created. This is called deferred execution. You can also force a query to execute immediately, which is useful for caching query results.


1 Answers

You should use SELECT TOP n....

The Query<T> method has an optional parameter bool buffered = true, which when true loops through the full resultset, reading each row into a List<T>. You could make this parameter false, and the resulting IEnumerable<T> would be "deferred" in the sense that the db query would not be executed until you use it, and the rows would be retrieved from the db side "one at a time" (calls IDataReader.Read on each iteration).

So, yes, it can be "deferred". HOWEVER, you should still use TOP n because otherwise you would still execute and prepare the resultset for 10000 records on the db side, although you may transport only the first n rows of those to the client.

like image 89
Eren Ersönmez Avatar answered Nov 05 '22 23:11

Eren Ersönmez