Search code examples
linqiqueryabledelayed-execution

Force an IQueryable to execute?


I have a method that 'has no translation to SQL' that I want to perform on an IQueryable, is there a way to force the IQueryable to execute without having to store it in some intermediate class?


Solution

  • Is the problem that you want your method to execute locally rather than in the database? If so, AsEnumerable is your friend. It's a very simple method, something like:

    public IEnumerable<T> AsEnumerable(IEnumerable<T> source)
    {
        return source;
    }
    

    The important thing is that it makes the compile-time type of the result IEnumerable<T> rather than IQueryable<T>, which means any LINQ query operators you call after that will be the LINQ to Objects ones instead of LINQ to SQL.

    For example:

    var query = context.Employees
                       // Filtering performed in SQL
                       .Where(emp => emp.IsFullTime)
                       .AsEnumerable()
                       // Projection performed locally; ComputeSalary has no
                       // SQL equivalent
                       .Select(emp => new { Employee = emp,
                                            Salary = ComputeSalary(emp) });
    

    You could call ToList as suggested elsewhere, but if you're doing filtering and don't really need the full list in memory, calling AsEnumerable and filtering that result will be more efficient than loading everything first.