I'm trying to map my entity into a new structure.
My entity looks like:
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; }
}
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": "[...]"
}
},
...
}
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
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With