0

Are there any way to get the following expression to work in EF Core 3.1?

_db.Customers
   .Where(customer => customer.IsFavorite(userId))
   .ToList();

IsFavorite is a simple expression that compares multiple properties with the userId. This could obviously be rewritten as

_db.Customers
   .Where(customer => customer.Prop1 == userId || customer.Prop2 == userId)
   .ToList();

But i'd like to avoid duplicating this logic. Other uses are when filtering on child properties, such as:

_db.Orders
   .Where(order => order.Customer.IsFavorite(userId))
   .ToList();

Any suggestions?

JEV
  • 2,494
  • 4
  • 33
  • 47
Tommy Jakobsen
  • 2,323
  • 6
  • 39
  • 66
  • So you ask, how to combine multiple expressions into one ? Here are several approaches: https://stackoverflow.com/questions/457316/combining-two-expressions-expressionfunct-bool – Holger Dec 11 '19 at 09:27
  • If `Customer` is defined as a class you could just use an extension method. – Robin B Dec 11 '19 at 09:29
  • 2
    What's the problem you're running into? AFAIK you can use class methods in LINQ expressions, the problem however is that the data provider cannot translate it into SQL – MindSwipe Dec 11 '19 at 09:33
  • @MindSwipe That is the problem yes. Any ways to make it translateable? – Tommy Jakobsen Dec 11 '19 at 14:27
  • Making a method that returns the expression could maybe help, I'd need to check though. If it works it would solve the problem of the entirety being loaded while allowing you to reuse the code – MindSwipe Dec 11 '19 at 14:28
  • That is the goal yes. Would be much appreciated, although I would prefer if the method could return bool instead of an expression. – Tommy Jakobsen Dec 11 '19 at 14:48
  • Your other option would be to use [LINQKit](https://github.com/scottksmith95/LINQKit) which provides support for inline expansion of methods so that they can be later translated to SQL. `Customer.IsFavorite` would still need to return a `LambdaExpression`. – NetMage Dec 11 '19 at 19:55

0 Answers0