我在表之间有一个ManyToMany关系:
(一切都根据建议完成)
public IEnumerable<User> GetAll()
{
return _context.Users
.Include(x => x.UserTags)
.ThenInclude(z => z.Tag);
}
应用程序很深
[
{
"id": 1,
"username": "Jon",
"password": null,
"userTags": [
{
"userId": 1,
"user": {
...
我想得到:
[
{
"id": 1,
"username": "Bartek",
"password": null,
"userTags": [ // List of Tags ]
已编辑
目前我已完成以下操作
[HttpGet]
public IActionResult GetAll()
{
var users = _userService.GetAll();
List<UserDto> result = new List<UserDto>();
foreach (var user in users)
{
var tagDto = _mapper.Map<IList<TagDto>>(user.UserTags.Select(x => x.Tag));
var userDtos = new UserDto
{
Id = user.Id,
Username = user.Username,
Tags = tagDto
};
result.Add(userDtos);
}
return Ok(result);
}
但是没有内置的选项可以达到预期的效果吗?
答案 0 :(得分:1)
我针对这种情况构建了自己的Mapper:
public class MyMapper
{
public IList<UserDto> GetUserDto(IEnumerable<User> users, IMapper _mapper)
{
List<UserDto> result = new List<UserDto>();
foreach (var user in users)
{
var tagDto = _mapper.Map<IList<TagDto>>(user.UserTags.Select(x => x.Tag));
var userDtos = new UserDto
{
Id = user.Id,
Username = user.Username,
Tags = tagDto
};
result.Add(userDtos);
}
return result;
}
}
使用:(控制器)
private IMapper _mapper;
private MyMapper _myMapper;
public UsersController(IMapper mapper)
{
_mapper = mapper;
_curioMapper = new CurioMapper();
}
[HttpGet]
public IActionResult GetAll()
{
var users = _userService.GetAll();
var result = _myMapper.GetUserDto(users, _mapper);
return Ok(result);
}
答案 1 :(得分:0)
一个想法,假设“一切都根据建议完成”
public IEnumerable<User> GetAll()
{
return _context.Users
.Include(x => x.UserTags)
.ThenInclude(z => z.Tag);
}
此数据似乎表明
[
{
"id": 1,
"username": "Bartek",
"password": null,
"userTags": [ // List of Tags ]
您应该更改为此
public IEnumerable<User> GetAll()
{
return _context.Users
.Include(a => a.UserTags.Tags.Select(c => c.tagname));
}