1

I'm using Entity Framework and I have a query similar to this:

entitiesContainer.Entities.Where(e => inMemoryList.Contains(e.Field))

It works but I'm having performance issues. I spent some time profiling this and the performance degradation seems to be happening in the application and not in the database. Apparently this query gets compiled every time it is executed and I guess it is because of the way the Contains is being translated.

Do you know how I can avoid the query getting compiled every time?

Thanks.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Paul
  • 105
  • 1
  • 12
  • 1
    What kind of performance issue are you having? Compiling the query every time is almost certainly not going to be noticeable. How big is this list you are passing in? – DavidG Feb 21 '18 at 10:41
  • 1
    Possible duplicate of [Why is .Contains slow? Most efficient way to get multiple entities by primary key?](https://stackoverflow.com/questions/8107439/why-is-contains-slow-most-efficient-way-to-get-multiple-entities-by-primary-ke) – Igor Feb 21 '18 at 10:50
  • Possible duplicate of [Why does the Contains() operator degrade Entity Framework's performance so dramatically?](https://stackoverflow.com/q/7897630/1260204) – Igor Feb 21 '18 at 10:51
  • Or [Scalable Contains method for LINQ against a SQL backend](https://stackoverflow.com/q/24534217/861716). – Gert Arnold Feb 21 '18 at 10:54

1 Answers1

-1

The query gets compiled every time, because it has to generate an "IN (..., ..., ...)" statement from your in memory list that potentially changed.

I have solved a similar performance problem in the past by passing the list of values as a parameter to a stored procedure, and having the stored procedure return the correct field list to be mapped as an entity result.

H. Lowette
  • 314
  • 1
  • 9