Skip to content

Translate parameterized collections to inline collections of parameters, with optional bucketization #34346

Closed

Description

@roji

When a collection parameter is referenced in a LINQ query, we currently allow it to be either parameterized in SQL (e.g. converted to a JSON array and processed with OPENJSON), or constantized (constant values integrated as-is in the SQL). Each method has its advantages and disadvantages (constantized queries allow for better query plans, parameterized queries have a single SQL and are better for plan/query caching).

A 3rd mode would be to integrate the values as SQL parameters, into an inline SQL collection (e.g. IN (@p1, @p2, @p3); this would allow the database the ability to take the collection's cardinality when planning (like the constantization option). As a further optimization on top, to partially mitigate the different-SQLs problem for collections of varying sizes, we'd have different sizing steps (or "buckets", e.g. 1, 5, 10, 20...); collections with e.g. 3 items would have their last item repeated to arrive at the next bucket size (5).

-- Constantization:
SELECT * FROM foo WHERE x IN (1, 2, 3);

-- Full parameterization:
SELECT * FROM foo WHERE x IN (SELECT v FROM OPENJSON(@values))

-- Inline collection with parameters:
SELECT * FROM foo WHERE x IN (@p1, @p2, @p3);

-- Inline collection with parameters, with bucketization:
SELECT * FROM foo WHERE x IN (@p1, @p2, @p3, @p3, @p3);

Notes:

  • We support parameterized collections not just in Contains, but in arbitrary LINQ querying. Since bucketization duplicates the last value, we can only do this in very query scenarios - mainly Contains; for example, we can't do this when Count() is composed on top of a parameterized collection.
  • We may consider making this mode the default, based on further perf investigations (#34347).
  • We have a report of inline collections of parameters being sometimes worse for query planning than constants (comment). We don't fully understand this yet, but this would obviously be important to understand, especially if we consider making this the default.
  • Since 8.0, users can already produce inline collections of parameters in SQL: Where(b => new[] { p1, p2, p3 }; but this works only if the size is fixed in the .NET collection. This issue is about having EF produce the same SQL but for when the entire .NET collection is parameterized in the LINQ query.

Activity

  1. added this to the Backlog milestone on Aug 3, 2024
  2. PaulVrugt commented on Aug 3, 2024

    @PaulVrugt

    This seems like a very good idea

  3. IanKemp commented on Aug 5, 2024

    @IanKemp

    How are you planning to implement this "bucketization"? Would the "bucket size" (e.g. 5 in the example) be specified by the end-user on a per-method-call basis, or as a configuration option in the DbContext, or is this something that EF Core would internally handle, or...? Obviously it's very early on but just trying to get a feel for what the team is thinking here WRT API shape and user control. - keeping in mind how the lack of user control around openjson has bit all involved.

  4. ErikEJ commented on Aug 5, 2024

    @ErikEJ
    Contributor
  5. ErikEJ commented on Aug 5, 2024

    @ErikEJ
    Contributor
  6. ErikEJ commented on Aug 5, 2024

    @ErikEJ
    Contributor
  7. roji commented on Aug 5, 2024

    @roji
    MemberAuthor

    @IanKemp we'd probably provide both a context option to configure the default bucket size, and also a per-collection configuration as well - similar to how we're implementing context-wide and per-collection configurability for constantization/parameterization in 9 (see #32394 (comment)).

    Note that this technique needs to be compared with just going back to full constantization, but with SQL Server RECOMPILE (see #34347). Inline collection with parameters does allow caching query plans where the collection cardinality is the same, but may also have some performance drawbacks and still causes some plan bloat (for different cardinalities).

  8. dazinator commented on Mar 20, 2025

    @dazinator
  9. 7 remaining items

  10. m-gasser commented on Jul 23, 2025

    @m-gasser

    Users can already choose which strategy they want globally

    True, but I would argue, choosing a strategy is not what the users actually want (even if that is what is requested). I think users want stuff to just work, and if in rare case it does not, have a way to fix individual queries.

    If I'm understanding you right, you'd like an unspecified default value on the enum so that providers can implement some arbitrary behavior that isn't one of the 3 built-in strategies

    Exactly! As I see it, choosing a strategy is about patching shortcomings of the various databases and this is inherently provider specific. What is optimal can even vary over different major versions of a database. For example Postgres has (I heard) a query plan cache, that is relatively robust against thrashing and thus just always use parametrized IN might make sense there. For SQL Server this will likely not work so well (I would really like to know this for a fact, but we are not gonna risk our production database to find out). For SQL Server also just using OPENJSON does not work so well (this is what you got feedback for). Constantization is the worst, that was actually the main problem we had to work around initially, when we wanted to allow our developers to use EF Core on our smaller databases. Constantization is definitely not a good global default on SQL Server, but it might be on other databases!

    In summary, at least for SQL Server, all of the options solve some issues, but cause others, basically making all of them suboptimal as global default. But it does not have to be this way, Dapper chooses to mix strategies to reach a better overall solution and so does our internal ORM.

    we won't be able to do this in time for EF 10.

    That's a bummer.

  11. roji commented on Jul 23, 2025

    @roji
    MemberAuthor

    What is optimal can even vary over different major versions of a database. For example Postgres has (I heard) a query plan cache, that is relatively robust against thrashing and thus just always use parametrized IN might make sense there.

    Not really - the same fundamental problem affects PostgreSQL as well: if you execute the same query multiple times with a parameterized array and the cardinality varies widely, you can get stuck with a generic plan that was optimized for a certain cardinality, and queries that significantly deviate from that cardinality could perform very poorly.

    In theory, it's true that a database may do specific optimizations around this problem, e.g. automatically taking into account parameterized array cardinality and "bucketizing" plans (on plan for 1-10 parameters, then another for 10-100). But no database actually does this as far as I'm aware, and so I'm not sure actually varying behavior by provider makes too much sense. But I'm indeed looking into what would be optimal for PostgreSQL (see npgsql/efcore.pg#3269).

    So again in theory, while this looks like something where different databases may want to do completely different things (and they can if they really want to), in practice that doesn't seem to be the case, at least not right now.

    Dapper chooses to mix strategies to reach a better overall

    Can you point me to a source on this? As far as I'm aware, Dapper simply always does inline parameters (it doesn't do OPENJSON ever, that didn't even exist when Dapper was written).

  12. m-gasser commented on Jul 23, 2025

    @m-gasser

    Thanks for your insights about PostgreSQL, so the grass is not greener on the other side.

    Dapper simply always does inline parameters (it doesn't do OPENJSON ever, that didn't even exist when Dapper was written).

    You are right, I misremembered, however there is a threshold for when to stop using parametrization. The switch is to STRING_SPLIT however, not OPENJSON, and the setting for it is disabled by default.
    Having it off by default makes sense to maximize compatibility to older SQL Server versions and setting a default would likely require a major version bump of Dapper to not be too risky. I did not find anything, what threshold Stack Overflow is using internally and the closest to a recommendation I found was DapperLib/Dapper#1431 (comment). So as a random guess, the value of 5 is what is used internally at Stack Overflow.

  13. roji commented on Jul 23, 2025

    @roji
    MemberAuthor

    Note that we already switch to OPENJSON once we pass SQL Server's parameter threshold (you can't have more than 2100 parameters per command), so in a sense we're already doing what you propose. Of course it may make sense to adjust the threshold to something much lower - we can definitely consider that for the future.

  14. dazinator commented on Jul 26, 2025

    @dazinator

    @roji
    Just wanted to share my experience on a topic you mentioned:

    if you execute the same query multiple times with a parameterized array and the cardinality varies widely, you can get stuck with a generic plan that was optimized for a certain cardinality, and queries that significantly deviate from that cardinality could perform very poorly.

    We've been hit by this same issue simply using global query filters and a different TenantId.
    Due to parameter sniffing and plan cache reuse on sql sever, and tenants with wildly different volumes of records.

    1. First query with TenantId = 1 has no records. Plan is cahced
    2. Second query with TenantId = 2 has a million records. Suboptimal Plan from above is used and times out.

    At some arbitrary point in time sql sorts a new plan and things are working smoothly again (or not).

    After fighting this issue, aside from further optimisation work, our quick fix solution was

    1. Wrote an extension so that we can tack on Option(RECOMPILE) hint into the sql produced for specific EF core queryables.

    This seemed to solve the issue but ofcourse now we don't get the benefit of any Plan caching at all for those queries.

    What we really wanted was a plan cache per tenant id but it was not obvious how to achieve this..

    Later we found a solution that came with various tradeoffs. We use per tenant (child) DI containers, and its possible for us to have EF core dbcontext models registered and built and isolated per tenant. This means the global query filter configured for each model can be a constant expression for its specific tenant id. When doing this it eliminated parameter sniffing of the Tenant Id and as it was a Literal in the query it means each tenants queries were now seperate with their own plans.

    The downside is more memory and complexity having per tenant containers - something we try to reduce when possible.

    What might help: when configuring a global query filter, I couldnt figure out how to make EF core submit a variable established at runtime (Tenant id from current tenant context) as a Literal in the query. If we could achieve this we could potentially move EF core dbcontexts back into the main application container as opposed to the per tenant one.

  15. zdenek-jelinek commented on Jul 26, 2025

    @zdenek-jelinek

    I think you can already (EF Core 8+) do what you describe with EF.Constant. In eariler versions, you could also hand-roll the filter expression and use Expression.Constant which is way more involved.

    So as a result, the Tenant ID you mention becomes a constant in the query while the other scalars stay parametrized (if appropriate). This way, you get a query plan per tenant. This became common practice for us with EF Core, SQL Server and large datasets with skewed statistics (basically what you describe with one tenant being small while other being large).

    A similar thing can be done with collections. The options are being extended for EF Core 10 in #34347 as there are more parameterization options with collections.

  16. roji commented on Jul 26, 2025

    @roji
    MemberAuthor

    @dazinator thanks for the description of your scenario - that all makes perfect sense, and multi-tenancy is indeed known to be particularly tricky when it comes to bad cached plans (due to potentially very different data profiles across tenants).

    @zdenek-jelinek's suggestion here should work. EF.Constant used to be applied very early - way before query filters were applied - so it didn't use to be possible to have varying constant values for the same query (regardless of global query filters). But recently the working of EF.Constant was changed to be handled much later, making it possible for the same (cached) EF query to vary the constant values that get sent. This should also make it possible to use EF.Constant() in query filters - please give it a try and open a separate issue if you see any problems.

    I'll just point out that this conversation isn't specifically related to collections in any way.

  17. modified the milestones: Backlog, 10.0.0 on Jul 28, 2025
  18. ChairmanMawh commented on May 18, 2026

    @ChairmanMawh

    Hi Roji

    I had a quick question about the bucketization mentioned earlier in the thread; are there plans to introduce it at all? Should we do it ourselves by deciding our buckets and replicating one of the values in our collection up to a bucket size?

    e.g.

    var myBuckets = [3, 10, 25];
    var chosenBucket = myBuckets.Min(b => b > myIdsList.Count);
    while(myIdsList.Count < chosenBucket){
      myIdsList.Add[myIdsList[0]);
    }
    

    This should mean that EF always gets a collection of 3, 10 or 25 (unless more than 25, let's ignore that) and make only @p0 - @pBucketCount, i.e. only ever 3 queries in the cache (one with 3 params, one with 10 and one with 25) ?

  19. ErikEJ commented on May 18, 2026

    @ErikEJ
    Contributor

    @ChairmanMawh That is implemented in EFCore 10!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions