Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7641319
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T08:53:31+00:00 2026-05-31T08:53:31+00:00

Entity Framework always seems to use constants in generated SQL for values provided to

  • 0

Entity Framework always seems to use constants in generated SQL for values provided to Skip() and Take().

In the ultra-simplified example below:

int x = 10;
int y = 10;

var stuff = context.Users
    .OrderBy(u => u.Id)
    .Skip(x)
    .Take(y)
    .Select(u => u.Id)
    .ToList();

x = 20;

var stuff2 = context.Users
    .OrderBy(u => u.Id)
    .Skip(x)
    .Take(y)
    .Select(u => u.Id)
    .ToList();

the above code generates the following SQL queries:

SELECT TOP (10) 
[Extent1].[Id] AS [Id]
FROM ( SELECT [Extent1].[Id] AS [Id], row_number() OVER (ORDER BY [Extent1].[Id] ASC) AS [row_number]
    FROM [dbo].[User] AS [Extent1]
)  AS [Extent1]
WHERE [Extent1].[row_number] > 10
ORDER BY [Extent1].[Id] ASC

SELECT TOP (10) 
[Extent1].[Id] AS [Id]
FROM ( SELECT [Extent1].[Id] AS [Id], row_number() OVER (ORDER BY [Extent1].[Id] ASC) AS [row_number]
    FROM [dbo].[User] AS [Extent1]
)  AS [Extent1]
WHERE [Extent1].[row_number] > 20
ORDER BY [Extent1].[Id] ASC

Resulting in 2 Adhoc plans added to the SQL proc cache with 1 use each.

What I’d like to accomplish is to parameterize the Skip() and Take() logic so the following SQL queries are generated:

EXEC sp_executesql N'SELECT TOP (@p__linq__0) 
[Extent1].[Id] AS [Id]
FROM ( SELECT [Extent1].[Id] AS [Id], row_number() OVER (ORDER BY [Extent1].[Id] ASC) AS [row_number]
    FROM [dbo].[User] AS [Extent1]
)  AS [Extent1]
WHERE [Extent1].[row_number] > @p__linq__1
ORDER BY [Extent1].[Id] ASC',N'@p__linq__0 int,@p__linq__1 int',@p__linq__0=10,@p__linq__1=10

EXEC sp_executesql N'SELECT TOP (@p__linq__0) 
[Extent1].[Id] AS [Id]
FROM ( SELECT [Extent1].[Id] AS [Id], row_number() OVER (ORDER BY [Extent1].[Id] ASC) AS [row_number]
    FROM [dbo].[User] AS [Extent1]
)  AS [Extent1]
WHERE [Extent1].[row_number] > @p__linq__1
ORDER BY [Extent1].[Id] ASC',N'@p__linq__0 int,@p__linq__1 int',@p__linq__0=10,@p__linq__1=20

This results in 1 Prepared plan added to the SQL proc cache with 2 uses.

I have some fairly complex queries and am experiencing significant overhead (on the SQL Server side) on the first run, and much faster execution on subsequent runs (since it can use the plan cache). Note that these more advanced queries already use sp_executesql as other values are parameterized so I’m not concerned about that aspect.

The first set of queries generated above basically means any pagination logic will create a new entry in the plan cache for each page, bloating the cache and requiring the plan generation overhead to be incurred for each page.

Can I force Entity Framework to parameterize values? I’ve noticed for other values e.g. in Where clauses, sometimes it parameterizes values, and sometimes it uses constants.

Am I completely out to lunch? Is there any reason why Entity Framework’s existing behavior is better than the behavior I desire?

Edit:
In case it’s relevant, I should mention that I’m using Entity Framework 4.2.

Edit 2:
This question is not a duplicate of Entity Framework/Linq to SQL: Skip & Take, which merely asks how to ensure that Skip and Take execute in SQL instead of on the client. This question pertains to parameterizing these values.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T08:53:33+00:00Added an answer on May 31, 2026 at 8:53 am

    Update: the Skip and Take extension methods that take lambda parameters described below are part of Entity Framework from version 6 and onwards. You can take advantage of them by importing the System.Data.Entity namespace in your code.

    In general LINQ to Entities translates constants as constants and variables passed to the query into parameters.

    The problem is that the Queryable versions of Skip and Take accept simple integer parameters and not lambda expressions, therefore while LINQ to Entities can see the values you pass, it cannot see the fact that you used a variable to pass them (in other words, methods like Skip and Take don’t have access to the method’s closure).

    This not only affects the parameterization in LINQ to Entities but also the learned expectation that if you pass a variable to a LINQ query the latest value of the variable is used every time you re-execute the query. E.g., something like this works for Where but not for Skip or Take:

    var letter = "";
    var q = from db.Beattles.Where(p => p.Name.StartsWith(letter));
    
    letter = "p";
    var beattle1 = q.First(); // Returns Paul
    
    letter = "j";
    var beattle2 = q.First(); // Returns John
    

    Note that the same peculiarity also affects ElementAt but this one is currently not supported by LINQ to Entities.

    Here is a trick that you can use to force the parameterization of Skip and Take and at the same time make them behave more like other query operators:

    public static class PagingExtensions
    {
        private static readonly MethodInfo SkipMethodInfo = 
            typeof(Queryable).GetMethod("Skip");
    
        public static IQueryable<TSource> Skip<TSource>(
            this IQueryable<TSource> source, 
            Expression<Func<int>> countAccessor)
        {
            return Parameterize(SkipMethodInfo, source, countAccessor);
        }
    
        private static readonly MethodInfo TakeMethodInfo = 
            typeof(Queryable).GetMethod("Take");
    
        public static IQueryable<TSource> Take<TSource>(
            this IQueryable<TSource> source, 
            Expression<Func<int>> countAccessor)
        {
            return Parameterize(TakeMethodInfo, source, countAccessor);
        }
    
        private static IQueryable<TSource> Parameterize<TSource, TParameter>(
            MethodInfo methodInfo, 
            IQueryable<TSource> source, 
            Expression<Func<TParameter>>  parameterAccessor)
        {
            if (source == null) 
                throw new ArgumentNullException("source");
            if (parameterAccessor == null) 
                throw new ArgumentNullException("parameterAccessor");
            return source.Provider.CreateQuery<TSource>(
                Expression.Call(
                    null, 
                    methodInfo.MakeGenericMethod(new[] { typeof(TSource) }), 
                    new[] { source.Expression, parameterAccessor.Body }));
        }
    }
    

    The class above defines new overloads of Skip and Take that expect a lambda expression and can hence capture variables. Using the methods like this will result in the variables being translated to parameters by LINQ to Entities:

    int x = 10;       
    int y = 10;       
    
    var query = context.Users.OrderBy(u => u.Id).Skip(() => x).Take(() => y);       
    
    var result1 = query.ToList();
    
    x = 20; 
    
    var result2 = query.ToList();
    

    Hope this helps.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm using Entity Framework and MS SQL Server 2008. It seems that Entity Framework
I'm using Entity Framework (1st time) on a SQL 2005 database for a data
I am using Entity Framework and SQL CE 4.0 with my WPF application. How
We're currently a Linq to SQL shop but evaluating Entity Framework. One thing that
Is there a way to create an association in entity framework that always applies
Goal: To use entity framework with N-tier in my WPF application. Problem: I can't
I have mapped Entity framework entities. Each table in SQL Server 2008 contains Timestamp
I use Entity framework for creating model. I have table hierarchy where User is
I'm trying to use Entity Framework for my model/data access, and running into speed
My problem is that when I get a SQL exception from the entity framework

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.