1

I would like to create a reusable method that I can use in Select() projections. Here is a simple example:

public partial class Product
{
    public IQueryable<ProductImage> GetProductImages(bool ActiveOnly)
    {
        return this.ProductImages.Where(i => !ActiveOnly || i.IsActive);
    }
}

public class App
{
    public void Main()
    {
        var product = db.Products.Select(p => new {
            p.Name,
            p.GetProductImages(true)
        }
    }
}

The above will fail with the standard LINQ to Entities does not recognize the method ... and I get that I can call db.Products.ToList().Select(...), but that is not what I am looking for, as in my case, I am projecting in order to avoid pulling unnecessary data into memory.

I have successfully been using Microsoft.Linq.Translations for custom properties for a while now, however that will not work in my example because I need to pass in a parameter, so a method is really the only way I can see this working. Any help is greatly appreciated.

Keith
  • 5,311
  • 3
  • 34
  • 50
  • See [Linq to entities extension method inner query (EF6)](http://stackoverflow.com/questions/39623788/linq-to-entities-extension-method-inner-query-ef6), [Projection of single entities in EF with extension methods](http://stackoverflow.com/questions/39623788/linq-to-entities-extension-method-inner-query-ef6) and linked/similar threads. – Ivan Stoev Sep 23 '16 at 17:36
  • I saw that one already, and it didn't provide a solution for a reusable method that returns a collection. – Keith Sep 23 '16 at 18:14
  • Well, then you have your answer, right :) Asking a question doesn't mean there is always a solution. – Ivan Stoev Sep 23 '16 at 18:24
  • No, I do not have my answer. – Keith Sep 23 '16 at 21:33
  • Read the StriplingWarrior answer (the first link - your question technically is duplicate). `p.GetProductImages(true)` is part of an expression tree, thus cannot be evaluated, hence cannot be converted to SQL. There is fundamental difference between expressions and delegates, although visually they look the same. – Ivan Stoev Sep 23 '16 at 21:48

0 Answers0