3

I have the following expression (simplified):

from p in Providers select new { p.Name, p.Accounts.Count(a => a.State == 2) };

This works fine, but now I want to create a reusable expression like so:

Expression<Func<Account, bool>> MyPredicate() { return a => a.State == 2; }

and use it like so:

from p in Providers select new { p.Name, p.Accounts.Count(MyPredicate()) }

This unfortunately doesn't work because the navigation property (Accounts) is an IList or ICollection in EF. What's the pattern here? Happy to change things around a little, but note that I'm not after dynamic expressions just reusable ones.

batkuip
  • 1,480
  • 3
  • 15
  • 25
  • 1
    its pretty non-trivial to do this actually in SQL, we did it once using linqkit – undefined Feb 14 '13 at 03:04
  • Ouch. That does look nasty indeed (http://www.albahari.com/nutshell/linqkit.aspx). It does explain the core issue which is nice to know. Unfortunately I haven't got their workarounds working within a select statement, maybe a limitation of linqkit. – batkuip Feb 14 '13 at 03:35
  • Could be, we definitally used it to get stuff back from the server, we were using it to calculate stats so it was in the result set but may have been outside the actual select statement – undefined Feb 14 '13 at 03:58
  • *Shameless cross-promotion* I just answered a related question here - http://stackoverflow.com/questions/14868607/dynamic-predicate-building-in-ef5/14894524#14894524. See my notes about generically adding fields as it can be a little bit tricky. That last link may be of particular interest http://www.codeproject.com/Articles/28580/LINQ-and-Dynamic-Predicate-Construction-at-Runtime – Aaron Newton Feb 15 '13 at 13:39

0 Answers0