且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

GroupBy自动映射器聚合

更新时间:2022-02-24 23:07:45

这是工作示例,您可以参考

Here is the working demo , you could refer to

设置配置文件

public class SettingsProfile:Profile
{
    public SettingsProfile()
    {
        CreateMap<IGrouping<string, Settings>, SettingsToReturnDto>()
            .ForMember(dest => dest.Domain, opt => opt.MapFrom(src => src.Key))
            .ForMember(dest => dest.Elements, opt => opt.MapFrom(src => src.ToList()));
        CreateMap<Settings, ElementsToReturnDto>();
    }
}

控制器

public class ValuesController : ControllerBase
{
    private readonly SeeMiddleContext _context;
    private readonly IMapper _mapper;

    public ValuesController(SeeMiddleContext context, IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }

    public IActionResult GetSettings()
    {
        List <IGrouping<string, Settings>> settingsFromDB = _context.Settings.GroupBy(s=>s.Property).ToList();

        var settingsToReturn = _mapper.Map<List<IGrouping<string, Settings>>,List<SettingsToReturnDto>>(settingsFromDB);

        return new JsonResult(settingsToReturn); 
    }
}