GroupBy自动映射器聚合

编程入门 行业动态 更新时间:2024-10-27 17:14:27
本文介绍了GroupBy自动映射器聚合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试将我的实体映射到新结构中.

I'm trying to map my entity into a new structure.

我的实体看起来像:

public class Settings { public int Id { get; protected set; } public int UserId { get; set; } string string Property{ get; set; } public string Element { get; set; } public string Value { get; set; } }

所以从数据库中会得到类似(其中值是一些基于json的值)

So from database would come something like (where value is some json based value)

UserId Property Element Value ----------- ---------- -------- ------ 15 std1 grid [...] 15 std1 panel [...] 15 std2 panel [...] 15 std2 grid [...] 15 std4 panel [...] 15 std5 panel [...] 15 std12 grid [...]

我的目标是输出类似以下内容的结构:

My goal is to output something structured like:

{ "std1": { "Elements": { "grid": "[...]", "panel": "[...]" } }, "std2": { "Elements": { "grid": "[...]", "panel": "[...]" } }, "std4": { "Elements": { "panel": "[...]" } }, ... }

我创建了以下DTO以实现此目的:

I created the folling DTO's to achieve this:

public class SettingsToReturnDto { public string Domain { get; set; } public List<ElementsToReturnDto> Elements { get; set; } } public class ElementsToReturnDto { public string Element { get; set; } public string Value { get; set; } } }

我尝试使用自动映射器映射来实现此目的,但是我的所有尝试都未能转换为新结构

I tried to use a automapper mapping to achieve this, but all my attemps failed into convert into the new structure

您能指出我正确的方向吗? 谢谢

can you point me into the correct direction? thanks

推荐答案

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

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); } }

更多推荐

GroupBy自动映射器聚合

本文发布于:2023-11-04 12:05:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1557888.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:映射器   GroupBy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!