Automapper 在 GroupBy 之后使用 ProjectTo

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

这是实体和视图模型:

public class Journal
{
    public int Id { get; set; }
    public DateTime Date { get; set; }
    public int ProductId { get; set; }
    public string SKU { get; set; }
    public int Count { get; set; }

    public virtual Product Product { get; set; }
}
public class AnalysisVM
{
    public int ProductId { get; set; }
    public JObject SKU { get; set; }
    public int Count { get; set; }
}

我想像这样在 GroupBy 之后使用 AutoMapper ProjectTo 。

var results = await _context.Journals.Where(x => x.Date <= date)
                                     .GroupBy(x => new { x.ProductId, x.SKU })
                                     .ProjectTo<AnalysisVM>(_mapper.ConfigurationProvider)
                                     .ToListAsync();

根据此 LINQ GroupBy 与 AutoMapper 的聚合

我创建映射器配置文件

CreateMap<string, JObject>().ConvertUsing(s => JObject.Parse(s));

CreateMap<IEnumerable<Journal>, AnalysisVM>()
    .ForMember(dest => dest.ProductId, opt => opt.MapFrom(src => src.FirstOrDefault().ProductId))
    .ForMember(dest => dest.SKU, opt => opt.MapFrom(src => src.FirstOrDefault().SKU))
    .ForMember(dest => dest.Count, opt => opt.MapFrom(src => src.Sum(x => x.Count)));

但是事情出了问题。如何使用ProjectTo到GroupBy?

[2024-03-04 16:59:36 DBG 47] <Microsoft.EntityFrameworkCore.Query> Compiling query expression: 
'DbSet<Journal>()
    .Where(x => x.Date <= __date_0)
    .GroupBy(x => new { 
        ProductId = x.ProductId, 
        SKU = x.SKU
     })
    .Select(dtoIGrouping`2 => new Object_7062817___SKU{ __SKU = dtoIGrouping`2.FirstOrDefault().SKU }
    )
    .Select(dtoLet => new AnalysisVM{ 
        ProductId = dtoIGrouping`2.FirstOrDefault().ProductId, 
        SKU = JObject.Parse(dtoLet.__SKU), 
        Count = dtoIGrouping`2.Sum(x => x.Count)
    }
    )' 

[2024-03-04 16:59:36 ERR 47] <Web.Infrastructure.Filters.HttpGlobalExceptionFilter> The LINQ expression 'dtoIGrouping`2' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information. 

套装版

“AutoMapper”版本=“12.0.1”

“Microsoft.EntityFrameworkCore”版本=“6.0.13”

“Pomelo.EntityFrameworkCore.MySql”版本=“6.0.2”

c# entity-framework-core automapper
1个回答
0
投票

JObject
的“自动”映射是问题所在:

CreateMap<string, JObject>().ConvertUsing(s => JObject.Parse(s));

尝试内联它(对我来说适用于最新的 EF Core 和自动映射器):

CreateMap<IEnumerable<Journal>, AnalysisVM>()
    .ForMember(dest => dest.SKU, opt => opt.MapFrom(src => JObject.Parse(src.FirstOrDefault().SKU)))
    // ... 
    ;

就我个人而言,我会在这里使用“手动”投影,这也将允许使用分组键来潜在地生成更好的 SQL。

© www.soinside.com 2019 - 2024. All rights reserved.