Export (0) Print
Expand All
1 out of 1 rated this helpful - Rate this topic

How to: Convert a Type to a Generic IEnumerable (LINQ to SQL)

Use AsEnumerable<TSource> to return the argument typed as a generic IEnumerable.

In this example, LINQ to SQL (using the default generic Query) would try to convert the query to SQL and execute it on the server. But the where clause references a user-defined client-side method (isValidProduct), which cannot be converted to SQL.

The solution is to specify the client-side generic IEnumerable<T> implementation of where to replace the generic IQueryable<T>. You do this by invoking the AsEnumerable<TSource> operator.

private bool isValidProduct(Product prod)
{
    return prod.ProductName.LastIndexOf('C') == 0;
}

void ConvertToIEnumerable()
{
    Northwnd db = new Northwnd(@"c:\test\northwnd.mdf");
    Program pg = new Program();
    var prodQuery =
        from prod in db.Products.AsEnumerable()
        where isValidProduct(prod)
        select prod;
}
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.