自动映射器未映射子集合中的所有子实体

时间:2019-03-25 14:09:07

标签: c# automapper

我在尝试使用Automapper映射实体时遇到问题。

我已经具有以下映射,其中“ GearLevel”具有“ Gear”的集合,并且始终为6。

当我映射实体时,如果“齿轮”具有多个具有相同名称的实体,则它仅映射其中一个实体,因此我将仅映射这些实体之一。

我应该在映射中做其他事情来克服这个问题吗?如果是的话,我该如何配置呢?

    CreateMap<HeroViewModel, Hero>();
    CreateMap<TagViewModel, Tag>();
    CreateMap<AbilityViewModel, Ability>();
    CreateMap<StatViewModel, Stat>();
    CreateMap<GearLevelViewModel, GearLevel>();
    CreateMap<GearViewModel, Gear>();

    CreateMap<HeroViewModel, RegisterNewHeroCommand>()
        .ConstructUsing(c => new RegisterNewHeroCommand(c.Name, c.Damage))
        .ForMember(dest => dest.Tags, opt => opt.MapFrom(src => src.Tags))
        .ForMember(dest => dest.Abilities, opt => opt.MapFrom(src => src.Abilities))
        .ForMember(dest => dest.Stats, opt => opt.MapFrom(src => src.Stats))
        .ForMember(dest => dest.GearLevels, opt => opt.MapFrom(src => src.GearLevels));

我正在以下代码中调用AutoMapper,当它调用映射器时,“ viewModel”在“ GearLevel”中具有所有“ Gear”,但是在“ registerCommand”返回时,它在“ GearLevel”具有相同的名称。

public async Task Register(HeroViewModel viewModel)
{
    try
    {
         var registerCommand = _mapper.Map<RegisterNewHeroCommand>(viewModel);
         await _mediator.SendCommand(registerCommand);
    }
    catch (Exception exception)
    {
        _logger.LogError(exception, $"Failed to register '{viewModel.Name}'");
    }
}

这使用以下实体:

public class HeroViewModel
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public int? Damage { get; set; }
    public List<TagViewModel> Tags { get; set; }
    public List<AbilityViewModel> Abilities { get; set; }
    public List<StatViewModel> Stats { get; set; }
    public List<GearLevelViewModel> GearLevels { get; set; }
}

public class GearLevelViewModel
{
    public Guid Id { get; set; }
    public int? Level { get; set; }
    public List<GearViewModel> Gear { get; set; }
}

public class GearViewModel
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}

以及以下命令:

public class RegisterNewHeroCommand : HeroCommand
{
    public RegisterNewHeroCommand(string name, int? damage)
    {
        Name = name;
        Damage = damage;
    }
}

public abstract class HeroCommand : Command
{
    public Guid Id { get; protected set; }
    public string Name { get; protected set; }
    public int? Damage { get; protected set; }
    public List<Tag> Tags { get; protected set; }
    public List<Ability> Abilities { get; protected set; }
    public List<Stat> Stats { get; protected set; }
    public List<GearLevel> GearLevels { get; protected set; }
}

0 个答案:

没有答案