我有以下要映射到Dto的实体结构
上下文实体
public class CallPoint
{
public int Id { get; set; }
public string Name {get; set;}
public ICollection {UserCallPoint} UserCallPoints {get; set;}
}
public class UserCallPoint
{
public int Id {get; set;}
public CallPoint CallPoint {get; set;}
public User User {get; set;
}
public class User
{
public int Id {get; set;}
public string Email {get; set;}
public ICollection<UserCallPoint> UserCallPoints {get; set;
}
DTO
public class CallPointDto
{
public int Id { get; set; }
public string Name { get; set; }
public List<UserDto> Users { get; set; }
}
public class UserDto
{
public int Id { get; set; }
public string Email { get; set; }
public List<CallPointDto> CallPoints { get; set; }
}
所以基本上我有很多对多的映射,但中间有一个实体基本上充当查找表。我该如何进行映射?我目前只是循环和映射如下,但它太慢了
private List<CallPointDto> MapCallPoint(List<CallPoint> callPoints)
{
List<CallPointDto> callPointDtos = new List<CallPointDto>();
foreach (var callPoint in callPoints)
{
var callPointDto = _mapper.Map<CallPointDto>(callPoint);
callPointDto.Users = new List<UserDto>();
foreach (var item in callPoint.UserCallPoints)
{
UserDto userDto = _mapper.Map<UserDto>(item.User);
callPointDto.Users.Add(userDto);
}
callPointDtos.Add(callPointDto);
}
return callPointDtos;
}
如何使用自定义解析器执行此操作?
答案 0 :(得分:0)
由于n:m关系可以无休止地运行的问题,我无法给出您正在寻找的答案。但我建议你使用这样的不同子DTO:
public class CallPointBaseDto
{
public int Id { get; set; }
public string Name { get; set; }
}
public class CallPointDto : CallPointBaseDto
{
public List<UserBaseDto> Users { get; set; }
}
public class UserBaseDto
{
public int Id { get; set; }
public string Email { get; set; }
}
public class UserDto : UserBaseDto
{
public List<CallPointBaseDto> CallPoints { get; set; }
}
映射:
cfg.CreateMap<CallPoint, CallPointDto>()
.ForMember(dest => dest.Users, opt => opt.MapFrom(src => src.UserCallPoints.Select(ucp => ucp.User)));
cfg.CreateMap<User, UserBaseDto>();
这方面的缺点当然是你没有UserBaseDto中的CallPoints,但是如果你需要它,你可以明确地调用这个用户并以另一种方式映射它。