arthurspa arthurspa - 1 year ago 62
C# Question

c# IQueryable<T>.Take method is not limiting result on EF6 entity

I'm using linq and EntityFramework 6 to limit the number of records returned from database.

My test table,

, has a total of 20 records.

If I write:

var auditLogsList = context.AuditLogs.Take(10); // Type is IQueryable<AuditLog>
var listValues = auditLogsList.ToList();
var count = listValues.Count; // Correct output = 10

I get
equals to 10, which is the expected output.

But, I don't know why, if I call method Take in the next line:

var auditLogsList = context.AuditLogs; // Type is IQueryable<AuditLog>
var listValues = auditLogsList.ToList();
var count = listValues.Count; // Wrong output = 20

I get
equals to 20, which is the total number of records of the table and it's not what I expect.

I need to use it the second way.

Any ideas if it's a bug or am I missing something here?

Note: I'm using .NET Framework 4.6.1 and Entity Framework 6

Answer Source

This line:


Just creates an enumerator over 10 items - but you don't assign this anywhere, so it's thrown away.

Later on you do this:

var listValues = auditLogsList.ToList();

This is working with the whole list - hence why you get 20.

If you just want to take 10 items (as a list), you can change the above line to:

var listValues = auditLogsList.Take(10).ToList();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download