Entity Framework Core – Making RowNumber (More) Useful

In the blog post ROW_NUMBER Support we saw how to implement a custom function and in the previous post Improved Value Conversion Support we realized that inserting and selecting custom types is one thing but using them for filtering is something totally different.

In this article:

Entity Framework Core – Making RowNumber (More) Useful
Pawel Gerr is architect consultant at Thinktecture. He focuses on backends with .NET Core and knows Entity Framework inside out.
Let’s take a query from one of the previous posts and add a WHERE clause:
				
					var query = dbContext.OrderItems
                     .Select(i => new
                                  {  
                                     ...,
                                     RowNumber = EF.Functions.RowNumber(i.ProductId)
                                  })
                     .Where(i => i.RowNumber == 1);
				
			

When executing the query we get a SqlException because the SQL statement is not valid.

				
					SELECT
   ...,
   ROW_NUMBER() OVER(ORDER BY i.ProductId) AS RowNumber
FROM
   OrderItems AS i
WHERE
   ROW_NUMBER() OVER(ORDER BY i.ProductId) = CAST(1 AS bigint)
				
			

The ROW_NUMBER is not just in SELECT but in WHERE as well because EF cannot know that the main query should be put into a sub query before accessing RowNumber, i.e. something like:

				
					SELECT ...
FROM
(
   SELECT
      ...,
      ROW_NUMBER() OVER(ORDER BY i.ProductId) AS RowNumber
   FROM
      OrderItems AS i
) t
WHERE
  t.RowNumber = CAST(1 AS bigint)
				
			

Probably, the easiest way is to introduce a method that gives EF a hint that the previous query should be a sub query. Something like:

				
					var query = dbContext.OrderItems
                     .Select(i => new
                                  {  
                                     ...,
                                     RowNumber = EF.Functions.RowNumber(i.ProductId)
                                  })
                     .AsSubQuery()
                     .Where(i => i.RowNumber == 1);
				
			

Fortunately, we don’t have do much because internally the method AsQueryable (or rather the expression associated with it) does just that. We will just (shamelessly ab)use it:

				
					public static class MyQueryableExtensions
{
   private static readonly MethodInfo _asQueryableMethodInfo 
                  = typeof(Queryable)
                      .GetMethods(BindingFlags.Public | BindingFlags.Static)
                      .Single(m => m.Name == nameof(Queryable.AsQueryable)
                                   && m.IsGenericMethod);

   public static IQueryable<TEntity> AsSubQuery<TEntity>(
                         this IQueryable<TEntity> source)
   {
      if (source == null)
         throw new ArgumentNullException(nameof(source));

      if (!(source.Provider is EntityQueryProvider))
          return source;

      var methodCall = Expression.Call(
                              null, 
                              _asQueryableMethodInfo.MakeGenericMethod(typeof(TEntity)),
                              source.Expression);

      return source.Provider.CreateQuery<TEntity>(methodCall);
   }
}
				
			

Having the method AsSubQuery we get the expected results.

Free
Newsletter

Current articles, screencasts and interviews by our experts

Don’t miss any content on Angular, .NET Core, Blazor, Azure, and Kubernetes and sign up for our free monthly dev newsletter.

Related Articles
.NET
Roslyn Source Generators: Logging – Part 11
In previous part we lerned how to pass parameters to a Source Generator. In this article we need this knowledge to pass futher parameters to implement logging.
29.08.2023
.NET
Roslyn Source Generators: Configuration – Part 10
In this article we will see how to pass configuration parameters to a Roslyn Source Generator to control the output or enable/disable features.
29.08.2023
.NET
Roslyn Source Generators: Reduction of Resource Consumption in IDEs – Part 9
In this article we will see how to reduce the resource consumption of a Source Generator when running inside an IDE by redirecting the code generation to RegisterImplementationSourceOutput.
29.08.2023