GroupBy automapper aggregation

前端 未结 1 1619
灰色年华
灰色年华 2021-01-20 09:44

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

My entity looks like:

public class Settings
    {
        public int Id { get; protected set; }
          


        
相关标签:
1条回答
  • 2021-01-20 10:12

    Here is the working demo , you could refer to

    SettingsProfile

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

    Controller

    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); 
        }
    }
    
    0 讨论(0)
提交回复
热议问题