我正在调用 API 来获取有关曲棍球比赛的信息。 API 的响应反序列化为以下内容:
public class GameResponseModel
{
public int Id { get; set; }
public DateTime Start { get; set; }
public TeamResponseModel HomeTeam { get; set; }
public TeamResponseModel AwayTeam { get; set; }
public List<PlayerResponseModel> HomeTeamRoster { get; set; } // <------ FROM
public List<PlayerResponseModel> AwayTeamRoster { get; set; }
}
但是,我更愿意将各自的名单代表为团队的财产,如下所示:
public class Game {
public int Id { get; set; }
public DateTime Start { get; set; }
public Team HomeTeam { get; set; }
public Team AwayTeam { get; set; }
}
public class Team
{
public string Name { get; set; }
public string Location { get; set; }
public List<Player> Roster { get; set; } // <------ TO
}
如何将
GameResponseModel.HomeTeamRoster
映射到 Game.HomeTeam.Roster
?例如
CreateMap<PlayerResponseModel, Player>();
CreateMap<TeamResponseModel, Team>();
CreateMap<GameResponseModel, Game>()
.ForMember(dest => dest.HomeTeam.Roster, opt => opt.MapFrom(src => src.HomeTeamRoster))
.ForMember(dest => dest.AwayTeam.Roster, opt => opt.MapFrom(src => src.AwayTeamRoster));
这是一个带有 AutoMapper.Extensions.Microsoft.DependencyInjection (12.0.0) 的 .NET 7 项目。
.AfterMap()
实现这一点:
CreateMap<GameResponseModel, Game>()
.AfterMap((src, dest) => {
dest.HomeTeam.Roster = src.HomeTeamRoster;
dest.AwayTeam.Roster = src.AwayTeamRoster;
});
您需要添加一个映射器:PlayerEntity -> Player,然后自动映射器就会知道如何映射这些。