1

I have this entity, lets call it Car, which I have created a filter for.

   public static Expression<Func<Car, bool>> FilterCars(int something) { ...}

It works when I query the database like this:

Repository.GetAll<Car>().Where(FilterCars(1));

The problem is that i also have this one-to-one relation where i would like to reuse this filter.

Lets say that a person only have one car, and I only want people who owns car that matches my filter, almost like this:

Repository.GetAll<Person>().Where(p => p.Car.Matches(FilterCars(1));

I have invented the matches method. But it is something like that I am looking for.

Does anyone know a way to "filter a single object" in a database query?

Moddaman
  • 2,538
  • 3
  • 23
  • 41
  • Does anyone know a way of ... ? – Fabjan Apr 27 '17 at 12:18
  • 3
    EF does not support custom methods (like your *invented*) inside expression trees. If you want to reuse expressions, you'll need some expression composition helpers. You can take a look at [LINQKit](http://www.albahari.com/nutshell/linqkit.aspx) package. Or some expression composing helpers posted on SO. For instance, you can take the helpers from my answer to [Define part of an Expression as a variable in c#](http://stackoverflow.com/questions/35012607/define-part-of-an-expression-as-a-variable-in-c-sharp/35015043#35015043) and use it like `.Where(FilterCars(1).ApplyTo((Person p) => p.Car))` – Ivan Stoev Apr 27 '17 at 12:28
  • Your helper worked like a charm! Thanks :) Post it as an answer – Moddaman Apr 27 '17 at 12:37
  • 1
    @Moddaman Glad it helped you :) But posting a duplicate answers is not tolerated here, so let keep it as it is. – Ivan Stoev Apr 27 '17 at 12:42

0 Answers0