Am I misunderstanding LINQ to SQL .AsEnumerable()?

前端 未结 5 652
遥遥无期
遥遥无期 2020-11-28 07:21

Consider this code:

var query = db.Table
              .Where(t => SomeCondition(t))
              .AsEnumerable();

int recordCount = query.Count();
int          


        
5条回答
  •  再見小時候
    2020-11-28 07:47

    Calling AsEnumerable() does not execute the query, enumerating it does.

    IQueryable is the interface that allows LINQ to SQL to perform its magic. IQueryable implements IEnumerable so when you call AsEnumerable(), you are changing the extension-methods being called from there on, ie from the IQueryable-methods to the IEnumerable-methods (ie changing from LINQ to SQL to LINQ to Objects in this particular case). But you are not executing the actual query, just changing how it is going to be executed in its entirety.

    To force query execution, you must call ToList().

提交回复
热议问题