Skip to content

When using GroupBy, getting "the given key 'EmptyProjectionMember' was not present in the dictionary" #31209

Closed

Description

@sam-wheat

Possibly related to:

#20277

#22089

#20929

#30905

Exception:

   System.Collections.Generic.KeyNotFoundException: The given key 'EmptyProjectionMember' was not present in the dictionary.
   at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
   at Microsoft.EntityFrameworkCore.Query.SqlExpressions.SelectExpression.ProjectionMemberToIndexConvertingExpressionVisitor.Visit(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.EntityShaperExpression.VisitChildren(ExpressionVisitor visitor)
   at Microsoft.EntityFrameworkCore.Query.SqlExpressions.SelectExpression.ProjectionMemberToIndexConvertingExpressionVisitor.Visit(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.SqlExpressions.SelectExpression.ApplyProjection(Expression shaperExpression, ResultCardinality resultCardinality, QuerySplittingBehavior querySplittingBehavior)
   at Microsoft.EntityFrameworkCore.Query.Internal.SelectExpressionProjectionApplyingExpressionVisitor.VisitExtension(Expression extensionExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryTranslationPostprocessor.Process(Expression query)
   at Microsoft.EntityFrameworkCore.SqlServer.Query.Internal.SqlServerQueryTranslationPostprocessor.Process(Expression query)
   at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](Expression query, Boolean async)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass9_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToQueryString(IQueryable source)
   at EmptyProjectionMemberTest.Program.Main(String[] args) in C:\Projects\EmptyProjectionMemberTest\EmptyProjectionMemberTest\Program.cs:line 26

Reproduce:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
	<OutputType>Exe</OutputType>
	<TargetFramework>net7.0</TargetFramework>
	<ImplicitUsings>enable</ImplicitUsings>
	<Nullable>enable</Nullable>
  </PropertyGroup>
	<ItemGroup>
		<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.5" />
		<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.5" />
	</ItemGroup>
</Project>




using Microsoft.EntityFrameworkCore;

namespace EmptyProjectionMemberTest;

internal class Program
{
	static async Task Main(string[] args)
	{
		DbContextOptionsBuilder builder = new();
		builder.UseSqlServer("Data Source=.;Initial Catalog=EmptyProjectionMemberTest;Integrated Security=True;MultipleActiveResultSets=True;Encrypt=false");
		Db db = new(builder.Options);
		await db.Database.EnsureDeletedAsync();
		await db.Database.EnsureCreatedAsync();

		try
		{
			var query = db.ReleaseDates
				.GroupBy(x => new { x.ReleaseID, x.DateReleased })
				.Select(x => x.First())
				.GroupBy(x => x.ReleaseID);

			string sql = query.ToQueryString(); // fails here

			var stuff = query.ToListAsync();
		}
		catch(Exception ex) 
		{
			Console.WriteLine(ex.ToString()); // The given key 'EmptyProjectionMember' was not present in the dictionary.
		}
	}
}


public class Db : DbContext
{
	public Db(DbContextOptions options) : base(options) { }

	public DbSet<ReleaseDate> ReleaseDates { get; set; }
}

public class ReleaseDate
{
	public int ID { get; set; }
	public string ReleaseID { get; set; }
	public DateTime DateReleased { get; set; }
}

Activity

  1. added this to the Backlog milestone on Jul 17, 2023
  2. hahn-kev commented on Oct 16, 2023

    @hahn-kev

    I'm also seeing this, my query is a little different though.

    queryable.GroupBy(s => s.EntityId)
    .Select(g => g.OrderByDescending(s => s.Commit.DateTime).First())
    .Select(s => s.Id)
    .ToArray()

    the second Select breaks everything, without the second select it works fine. This is a simplification but it has the same issue.

  3. ZoySoy commented on Nov 10, 2023

    @ZoySoy

    Hello. I also could reproduce "The given key 'EmptyProjectionMember' was not present in the dictionary" exception but on the little bit different example. I faced with this problem during migration from EntityFramework 6.4.4 to EF core. On EF 6.4.4 this query worked well. I have prepared similar repro example based on default blog/post example. There is failed query example:

    using var db = new BloggingContext();
    var posts = db.Posts
        .GroupBy(
            p => p.BlogId, 
            (id, list) => list.OrderByDescending(x => x.PostId).First())
        .Where(p => p.Title != null)
       .ToList();
    

    For this particular case the problem can be solved by moving Where(...) method before GroupBy(...), but maybe this case will help you to find initial problem anyway because, as I mentioned, it worked previously and I don't think that it is such an unusual query which shouldn't work.

    Frameworks:
    net6.0
    EntityFrameworkCore - 7.0.13

    Thanks in advance.

  4. lucasbode commented on May 3, 2024

    @lucasbode

    I encountered a similar error with a query like this...

    var results = Context.TruckModel
                .GroupBy(v => v.TruckModelId)
                .Select(g => g.OrderByDescending(x => x.Version).FirstOrDefault())
                .Where(t => t.Name == truckModelName)
                .ToList();
    

    It looks silly, but we were able to work around it by doing this...

    var groupedQuery = Context.TruckModel
                .GroupBy(v => v.TruckModelId)
                .Select(g => g.OrderByDescending(x => x.Version).FirstOrDefault());
    
    var results = Context.TruckModel.FromSqlRaw(groupedQuery.ToQueryString())
                .Where(t => t.Name == truckModelName)
                .ToList();
    
  5. lvyyln commented on Jul 3, 2024

    @lvyyln
  6. roji commented on Jul 3, 2024

    @roji
  7. kwakubiney commented on Jul 12, 2024

    @kwakubiney

    Facing similar issue with this:

         _dbContext.Crashes
                    .Where(x => x.ShopId == shopId)
                    .OrderByDescending(x => x.CreatedAt)
                    .GroupBy(t => t.SerialNumber)
                    .Select(g => g.First())
                    .AsNoTracking();
    

    EFCore 7.0.0
    .NET 6

  8. Khungersumit commented on Aug 10, 2024

    @Khungersumit

    Okay, so here is the discussion about this issue. I am having the same issue.

    query = groupBy(c=>some el)
    Select(g => g.OrderByDescending(m => m.CreatedAt).FirstOrDefault())

    // Culprit
    query= query.OrderByDescending(c => c.CreatedAt);

    This additional sorting operation seems to cause problems. Without this final sort, everything works as expected. I've spent hours trying to figure it out and even tried writing a raw SQL query, but that didn’t solve the problem either. I'm stumped! 🤔

  9. Khungersumit commented on Aug 10, 2024

    @Khungersumit

    Facing similar issue with this:

         _dbContext.Crashes
                    .Where(x => x.ShopId == shopId)
                    .OrderByDescending(x => x.CreatedAt)
                    .GroupBy(t => t.SerialNumber)
                    .Select(g => g.First())
                    .AsNoTracking();
    

    Resolved using @lucasbode 's approach although it looks clumsy. Tried the other approaches, didn't work:

        var groupedQuery = _dbContext.Crashes
                    .GroupBy(v => v.SerialNumber)
                    .Select(g => g.OrderByDescending(x => x.CreatedAt).FirstOrDefault());
    
                var results = _dbContext.Crashes.FromSqlRaw(groupedQuery.ToQueryString())
                    .Where(c => c.ShopId!= null && c.ShopId.Equals(shopId));
    

    EFCore 7.0.0 .NET 6

    Unfortunately, this workaround didn't pan out for me.

  10. TimFeldmann-Work commented on Aug 21, 2024

    @TimFeldmann-Work

    I am also running into this exact issue and spent the past 5 hours trying to find a workaround with no success.

  11. Khungersumit commented on Aug 21, 2024

    @Khungersumit

    I am also running into this exact issue and spent the past 5 hours trying to find a workaround with no success.

    can you share your query?

  12. 9 remaining items

  13. RichardD2 commented on Jun 6, 2025

    @RichardD2

    Scratch that workaround - I've just discovered that it actually breaks the projection!

    My projection loads the value of navigation properties from related entities. But when it's followed by the GroupBy, those properties are not included in the generated query, and are set to null.

    Eg:

    var limits = await context.ActivityLimits
        .Where(l => l.StartDate <= forDay)
        .Select(l => new { l.ActivityId, l.StartDate, ActivityName = l.Activity.Name })
        .GroupBy(l => l.ActivityId, (_, items) => items.OrderByDescending(l => l.StartDate).First())
        .ToListAsync();
    

    uses the query:

    SELECT [a3].[StartDate], [a3].[ActivityId], [a3].[Id], [a3].[CreatedBy], [a3].[CreatedDate], ..., [a3].[c]
    FROM (
        SELECT [a].[ActivityId]
        FROM [dbo].[ActivityLimits] AS [a]
        WHERE [a].[StartDate] <= @__forDay_0
        GROUP BY [a].[ActivityId]
    ) AS [a1]
    LEFT JOIN (
        SELECT [a2].[StartDate], [a2].[ActivityId], [a2].[Id], [a2].[CreatedBy], [a2].[CreatedDate], ..., [a2].[c]
        FROM (
            SELECT [a0].[StartDate], [a0].[ActivityId], [a0].[Id], [a0].[CreatedBy], [a0].[CreatedDate], ..., 1 AS [c], ROW_NUMBER() OVER(PARTITION BY [a0].[ActivityId] ORDER BY [a0].[StartDate] DESC) AS [row]
            FROM [dbo].[ActivityLimits] AS [a0]
            WHERE [a0].[StartDate] <= @__forDay_0
        ) AS [a2]
        WHERE [a2].[row] <= 1
    ) AS [a3] ON [a1].[ActivityId] = [a3].[ActivityId]
    

    This query includes all of the columns from the ActivityLimit entity, and none of the columns from the projection! The ActivityName on the projection is null for every row.


    It seems the real workaround is to rewrite the query as:

    var groupedLimits = context.ActivityLimits
        .Where(l => l.StartDate <= forDay)
        .GroupBy(l => l.ActivityId, (_, items) => items.OrderByDescending(l => l.StartDate).First());
    
    var projectedLimits = await context.ActivityLimits
        .Where(l => groupedLimits.Contains(l))
        .Select(l => new { l.ActivityId, l.StartDate, ActivityName = l.Activity.Name })
        .ToListAsync();
    

    This uses the query:

    SELECT [a].[StartDate], [a].[ActivityId], [a2].[Name] AS [ActivityName]
    FROM [dbo].[ActivityLimits] AS [a]
    INNER JOIN [dbo].[Activities] AS [a2] ON [a].[ActivityId] = [a2].[Id]
    WHERE [a].[Id] IN (
        SELECT (
            SELECT TOP(1) [a1].[Id]
            FROM [dbo].[ActivityLimits] AS [a1]
            WHERE [a1].[StartDate] <= @__forDay_0 AND [a0].[ActivityId] = [a1].[ActivityId]
            ORDER BY [a1].[StartDate] DESC)
        FROM [dbo].[ActivityLimits] AS [a0]
        WHERE [a0].[StartDate] <= @__forDay_0
        GROUP BY [a0].[ActivityId]
    )
    

    which correctly populates the projection.

  14. added theissue type on Jun 15, 2025
  15. dec123ac commented on Aug 22, 2025

    @dec123ac

    I am seeing what appears to be a variation on this defect. I receive this error message for an 'EmptyProjectionMember' even though I'm not expressly using a GroupBy() or OrderBy.

    I put together three examples. The first two work as expected by selecting the object directly and putting it in a list or selecting the object then putting it into an anonymous object and then tolist.

    The third LINQ gives the error. All it is doing differently is checking to see if the query's selected object is null but it should not be and there is not a null pointer exception along with it.

    var objone = (from att in _dbContext.ATTACHMENT
    let mtr = (from g in _dbContext.ATTACHMENT
    join a in _dbContext.A on g.ATTACHMENT_KEY equals a.ATTACHMENT_KEY
    join m in _dbContext.S on a.SERIAL_CODE equals m.SerialCode
    join n in _dbContext.M on m.SerialCode equals n.StationSerialCode
    where g.ATTACHMENT_KEY == att.ATTACHMENT_KEY
    select m
    ).FirstOrDefault()
    where att.ATTACHMENT_KEY == 56
    select new { result = mtr }
    ).ToList();

    var objtwo = (from att in _dbContext.ATTACHMENT
    let mtr = (from g in _dbContext.ATTACHMENT
    join a in _dbContext.A on g.ATTACHMENT_KEY equals a.ATTACHMENT_KEY
    join m in _dbContext.S on a.SERIAL_CODE equals m.SerialCode
    join n in _dbContext.M on m.SerialCode equals n.StationSerialCode
    where g.ATTACHMENT_KEY == att.ATTACHMENT_KEY
    select m
    ).FirstOrDefault()
    where att.ATTACHMENT_KEY == 56
    select mtr
    ).ToList();

    var error = (from att in _dbContext.ATTACHMENT
    let mtr = (from g in _dbContext.ATTACHMENT
    join a in _dbContext.A on g.ATTACHMENT_KEY equals a.ATTACHMENT_KEY
    join m in _dbContext.S on a.SERIAL_CODE equals m.SerialCode
    join n in _dbContext.M on m.SerialCode equals n.StationSerialCode
    where g.ATTACHMENT_KEY == att.ATTACHMENT_KEY
    select m
    ).FirstOrDefault()
    where att.ATTACHMENT_KEY == 56
    select
    new
    {
    result= !Equals(mtr, null) ? mtr : new THING(),
    }
    ).ToList();

  16. roji commented on Aug 23, 2025

    @roji
    Member

    @dec123ac please open a new issue with a runnable, minimal repro - a query fragment such as what you posted above isn't sufficient, and it's likely your error is unrelated due to the lack of GroupBy.

  17. changed the title [-]The given key 'EmptyProjectionMember' was not present in the dictionary[/-] [+]When using GroupBy, getting "the given key 'EmptyProjectionMember' was not present in the dictionary"[/+] on Aug 23, 2025
  18. henriquewr commented on Apr 20, 2026

    @henriquewr
    Contributor

    For everyone hitting this issue or any issue related to GroupBy (at least in the cases that came to mind right now) I found a workaround:

    dbSet.GroupBy(x => x.GroupByKey)

    can be rewritten as

    dbSet.Select(x => x.GroupByKey)
        .Distinct()
        .Select(x => new
        {
            Key = x,
            Group = dbSet.Where(d => d.GroupByKey == x).ToList()
        })
    

    Example:

    dbSet.GroupBy(x => x.Key)
        .Select(x => x.First())
        .Select(x => x.Something)
    

    becomes

    dbSet.Select(x => x.Key)
        .Distinct()
        .Select(x => 
            dbSet.Where(d => d.Key == x)
                .Select(d => d.Something)
                .First()
        )
    
  19. added a commit that references this issue on Jun 16, 2026
    3ae41e9
  20. modified the milestones: Backlog, 11.0.0 on Jun 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions