1

我有这个转换器类。

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;
    }
}

在我有----需要映射IEnumerable<StatsModel>的以下场景中,我如何返回?Listplayer.PlayerStats

[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

4

1 回答 1

0
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);
于 2013-10-03T18:50:26.817 回答