0

I have seen lot of posts talking about IEnumerable that it applies filtration in the memory and not in SQL server like IQueryable.

But,

I have table having 20 records out of only one has Id = '12345'.

When i do

IEnumerable<Customer> customer = _context.Customer.where(x => x.Id== '12345');

It returns 1 row and not of 20 rows. Why?

My understanding is it would return 20 rows initially, later on when i do

var result = customers.ToList(); 

It will return 1 record.

simbada
  • 940
  • 4
  • 24
  • 43
  • 1
    It doesn't return any rows. It returns an expression that will be evaluated when you iterate the results. That expression contains a "where" clause, which will be included in that evaluation. – David Mar 29 '17 at 17:43
  • 1
    You have a misunderstanding as to what "deferred execution" means. It does not meant that all 20 rows will be returned. Think of how expensive that would be for every query ever written in Entity Framework. What it does mean is that your query is just that: a query. It does not get executed until you force its execution via some form of iteration--be it a `foreach`, a `ToList`, a `ToArray`, etc. – Kenneth K. Mar 29 '17 at 17:44
  • 2
    Note also that just because `customer` is declared to be of type `IEnumerable` doesn't mean it can't hold an `IQueryable`. `IQueryable` implements `IEnumerable`: https://msdn.microsoft.com/en-us/library/system.linq.iqueryable(v=vs.110).aspx So regardless of whether you treat it as an `IEnumerable`, the underlying object is an `IQueryable` in your example. – David Mar 29 '17 at 17:46

1 Answers1

0

At this time, you do the where on your IQueryable interface. (Remember that the right side of = is earlier executed then the left side)

IEnumerable<Customer> customer = _context.Customer.Where(x => x.Id == 12345);

What you have read is something like that:

IEnumerable<Customer> customers = _context.Customer
IEnumerable<Customer> clientFiltered = customers.Where(x => x.Id == 12345);

If you want to do this as oneliner:

_context.Customer.AsEnumerable().Where(x => x.Id == 12345);

Note, in the later 2 cases, you have first casted it to IEnumerable, then do a more specific Where.

Christian Gollhardt
  • 16,510
  • 17
  • 74
  • 111
  • Aaaah that's the point i was missing. Basically writing one line IEnumerable with Where clause actually mean two lines query you mentioned above. So filtration is is in memory for IEnumerable correct? and thats the reason i am getting 1 filtered record instead of 20.correct? – simbada Mar 29 '17 at 17:57