尝试对列表使用AutoMapper会返回错误“索引超出范围”。

时间:2019-04-01 18:19:06

标签: c# list automapper mapper

我一直在尝试使AutoMapper与列表一起使用,但是每当尝试这样做时,它总是会返回相同的错误:

  

索引超出范围。必须为非负数且小于集合的大小。\ r \ n参数名称:index

我已经简化了代码,但是基本上,这些是我要映射到的类:

public class PlayerCar
{
    public string Manufacturer { get; set; }
    public string Name { get; set; }
}

public class Player
{
    public List<PlayerCar> Cars { get; set; }
    public string OwnerName { get; set; }
    public string OwnerUsername { get; set; }
}

这些是源类:

public class Users
{
    public int Id { get; set; }
    public string Username { get; set; }
    public Account User { get; set; }
}

public class Account 
{
    public string Name { get; set; }
    public List<UserCar> Cars { get; set; }
}

public class UserCar
{
    public string Manufacturer { get; set; }
    public string Name { get; set; }
    public int Year { get; set; }
    public string Colour { get; set; }
}

这是我一直在使用的映射器配置:

CreateMap<Users, Player>()
    .ForMember(c => c.OwnerUsername, opt => opt.MapFrom(c => c.Username))
    .ForMember(c => c.OwnerName, opt => opt.MapFrom(c => c.User.Name))
    .ForMember(c => c.Cars, opt => opt.MapFrom(c => c.User.Cars));

CreateMap<UserCar, PlayerCar>()
    .ForMember(c => c.Manufacturer, opt => opt.MapFrom(c => c.Manufacturer))
    .ForMember(c => c.Name, opt => opt.MapFrom(c => c.Name));

我不知道这是否会影响任何事情,但是我一直在做.ProjectTo<Player>(_mapper.ConfigurationProvider).

有人知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

列表是否在任何地方初始化了?

您不必为User Car到Player进行单独的显式映射吗?我不认为它会允许嵌套映射。

CreateMap<Player, Account>()
     .ForMember(p => p.Cars, opts => opts.MapFrom(a => a.Cars))

... ForMember(c => c.Cars, opt => opt.MapFrom(c => c.User));