none
Extension Methods in Linq Queries RRS feed

  • Question

  • I am using Linq2Sql as the Data Access for an app I am working with but I do not wan to use the Linq2Sql classes that were auto generated.

    I created a few extension methods for conversion to make the query code cleaner.

    My code looks like this

    public IQueryable<Product> GetProducts()  
    {  
        return from c in DC.Products select c.ToProduct();  

    the ToProduct() method converts the linq2sql class to my class.

    The problem is that it throws an exception saying the ToProduct method does not have a translation to SQL.

    I can get this to work right by writing it like this

    public IQueryable<Product> GetProducts  
    {  
         var Products = from p in DC.Products select p;  
         List<Product> List = new List<Product>();  
         foreach(var p in Products)  
         {  
              List.Add(p.ToProduct());  
         }  
         return List.AsQueryable();  

    This of course defeats the whole purpose of the deferred nature of Linq2Sql

    The only other option I can think of is to put the conversion in the query. But this is messy and will cause redundant conversion code for each query method.

    Any Ideas?

    Thanks
    Monday, December 29, 2008 5:17 PM