Am I misunderstanding LINQ to SQL .AsEnumerable()?

前端 未结 5 658
遥遥无期
遥遥无期 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:59

    Justin Niessner's answer is perfect.

    I just want to quote a MSDN explanation here: .NET Language-Integrated Query for Relational Data

    The AsEnumerable() operator, unlike ToList() and ToArray(), does not cause execution of the query. It is still deferred. The AsEnumerable() operator merely changes the static typing of the query, turning a IQueryable into an IEnumerable, tricking the compiler into treating the rest of the query as locally executed.

    I hope this is what is meant by:

    IQueryable-methods to the IEnumerable-methods (ie changing from LINQ to SQL to LINQ to Objects

    Once it is LINQ to Objects we can apply object's methods (e.g. ToString()). This is the explanation for one of the frequently asked questions about LINQ - Why LINQ to Entities does not recognize the method 'System.String ToString()?

    According to ASENUMERABLE - codeblog.jonskeet, AsEnumerable can be handy when:

    some aspects of the query in the database, and then a bit more manipulation in .NET – particularly if there are aspects you basically can’t implement in LINQ to SQL (or whatever provider you’re using).

    It also says:

    All we’re doing is changing the compile-time type of the sequence which is propagating through our query from IQueryable to IEnumerable – but that means that the compiler will use the methods in Enumerable (taking delegates, and executing in LINQ to Objects) instead of the ones in Queryable (taking expression trees, and usually executing out-of-process).

    Finally, also see this related question: Returning IEnumerable vs. IQueryable

提交回复
热议问题