我在表之间有一个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 ]
EDITED
目前我做了如下
[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);
}
但是没有任何内置选项可以达到预期的效果吗?
我为这种情况建立了自己的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);
}
只是一个想法,假设“一切都根据建议完成”
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));
}