AutoMapper映射这个特定的场景

我有这个转换器类。AutoMapper映射这个特定的场景

public class StatsConverter : TypeConverter<Tuple<Player,Stats>, StatsModel> 

, ITypeConverter<Stats, StatsModel>

{

protected override StatsModel ConvertCore(Tuple<Player, Stats> source)

{

var pm = new StatsModel

{

Id = source.Item2.Id,

PlayerId = source.Item1.Id,

DisplayName = source.Item2.DisplayName,

};

return pm;

}

}

如何在以下情况下,我有List ---- player.PlayerStats需要被映射回一个IEnumerable<StatsModel>

[HttpGet("{id:int}/PlayerStats", RouteName = "GetPlayerStats")] 

public IEnumerable<StatsModel> GetPlayerStats(int id)

{

var user = this._manager.GetPlayerById(id);

// I can retrieve a "List" of player.PlayerStats.

//But how do I map and return it?

return this._mapper.Map<IEnumerable<StatsModel>>(????)

}

当我这样做

return this._mapper.Map<IEnumerable<StatsModel>>(player.PlayerStats); 

我得到这个错误: Change the type converter source type, or redirect the source value supplied to the value resolver using FromMember

回答:

public class StatsConverter : ITypeConverter<Tuple<Player, Stats>, StatsModel> 

{

public StatsModel Convert(Tuple<Player, Stats> source)

{

return new StatsModel

{

Id = source.Item2.Id,

PlayerId = source.Item1.Id,

DisplayName = source.Item2.DisplayName,

};

}

}

首先确保您的转换器已指定。

Mapper.CreateMap<Tuple<Player,Stats>, StatsModel> 

.ConvertUsing<StatsConverter>();

我会从你的问题的假设,Player类结构(纠正我,如果我错了):

public class Player 

{

public int Id { get; set; }

public IEnumerable<Stats> PlayerStats { get; set; }

}

里面你的方法,你将需要得到的球员,统计分组在一起。

var user = _manager.GetPlayerById(id); 

// Expand the player stats

var playerStats = user.PlayerStats

.Select(stats => Tuple.Create(user, stats));

Mapper.Map<IEnumerable<Tuple<Player,Stats>>,

IEnumerable<StatsModel>>(playerStats);

以上是 AutoMapper映射这个特定的场景 的全部内容, 来源链接: utcz.com/qa/258293.html

回到顶部