2

Let's say that I have a table named Poll and I want to write a LINQ Extension to list all polls that have ID belong to an array. For e.g:

void Main()
{
    long[] ids = new long[]{ 1,2,3,4,5,6,7,8,9 };

    ListFail<Poll>(Poll, p => p.ID, ids); //Failed!
    ListOK<Poll>(Poll, p => p.ID, ids); //OK!
}

public void ListFail<T>(Table<T> obj, Func<T, long> idProperty, long[] ids) where T : class
{
    obj.Where(p => ids.Contains(idProperty(p))).ToList().Dump();
}

public void ListOK<T>(Table<T> obj, Func<T, long> idProperty, long[] ids) where T : class
{
    obj.ToList().Where(p => ids.Contains(idProperty(p))).ToList().Dump();
}

I don't know why I get the error on ListFail

Method 'System.Object DynamicInvoke(System.Object[])' has no supported translation to SQL.

and when I added the ToList() before Where then it run well on ListOK but of course I don't want to get the whole Poll table.

Any idea?

ByulTaeng
  • 1,269
  • 1
  • 21
  • 40

1 Answers1

2

Change Func<T, long> to Expression<Func<T, long>>. Right now, because of this, EF doesn't understand it.

Euphoric
  • 12,645
  • 1
  • 30
  • 44
  • I've changed it according to your suggestion but got another error `'idProperty' is a 'variable' but is used like a 'method'` – ByulTaeng Jun 05 '11 at 16:09
  • I'm sorry. I cant help you. Query composition can be ass sometimes and this looks like it wont be easy to implement. One thing that comes to mind is to create the expression tree by hand. But I dont have time for that. – Euphoric Jun 06 '11 at 06:04