从分组的 linq 查询投影时出错

问题描述 投票:0回答:1

我有一个数据库表,用于存储以下有关图像的数据:

  • 图片编号
  • 事件项目(父实体)Id
  • 图像二进制数据
  • 图像文件扩展名

我的目标是为每个(父)事件项检索一张图像,但不包含二进制数据。在 SO 上使用不同的答案,我拼凑了以下内容:

var eventImages = context.EventImages.AsNoTracking()
                    // Filter to specific parent Id's
                    .Where(ei => uniqueEventIds.Contains(ei.EventItemId))
                    // Get only one image per parent
                    .GroupBy(img => img.EventItemId, (key, g) => g.OrderBy(img => img.EventImageId).FirstOrDefault()) 
                    // Project the image fields without the binary data
                    .Select(img => new 
                                {
                                img.EventImageId,
                                img.EventItemId,
                                img.EventImageFileExtension,
                                })
                                .ToList();

但是它抛出一个我不明白的异常:

KeyNotFoundException:字典中不存在给定键“EmptyProjectionMember”。

System.Collections.Generic.Dictionary.get_Item(TKey 键)

如果我删除整个投影 (

.Select(...)
) 方面,查询的第一部分会返回两个图像,所有字段都已填充,所以我认为那部分是正确的。我不确定错误与什么有关。

c# linq entity-framework-core linq-to-sql
1个回答
0
投票

也许你的 .net 是旧版本。对于你的代码,我在 .net7 efcore 7 上试过它工作正常

试试这个,看看它是否有效

           var eventImages = context.EventImages.AsNoTracking()
           .Where(ei => uniqueEventIds.Contains(ei.EventItemId))
           .GroupBy(img => img.EventItemId) 
           .Select(x => x.FirstOrDefault())
           .Select(img => new 
               {
                   img.EventImageId,
                   img.EventItemId,
                   img.EventImageFileExtension,
               }).ToList();
© www.soinside.com 2019 - 2024. All rights reserved.