无法从一个 ViewModel 映射到另一个

Unable to map from one ViewModel to another

我正在制作一个复选框列表来更新用户的角色,我正在尝试从中映射:

public class ApplicationRoleViewModel
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string NormalizedName { get; set; }
    public string ConcurrencyStamp { get; set; }
    public int SortOrder { get; set; }
    public string DisplayName { get; set; }
    public string Description { get; set; }
    public string Icon { get; set; } // Font Awesome-ikoner, f.eks. "fa-user"
}

对此:

public class SelectableRoleViewModel
{
    public Guid Id { get; set; }
    public string DisplayName { get; set; }
    public bool Selected { get; set; }
}

这是我的映射:

CreateMap<ApplicationRoleViewModel, SelectableRoleViewModel>()
    .ForMember(dest => dest.Id, s => s.MapFrom(i => i.Id))
    .ForMember(dest => dest.DisplayName, s => s.MapFrom(d => d.DisplayName))
    .ForMember(dest => dest.Selected, i => i.Ignore());

在控制器中这样映射:

ApplicationRole role = await db.Roles.FirstOrDefaultAsync();
SelectableRoleViewModel sr = auto.Map<SelectableRoleViewModel>(role);

给我以下错误信息:

AutoMapperMappingException: Missing type map configuration or unsupported mapping.

我在 Startup.cs 中注册 AutoMapper 是这样的:

services.AddAutoMapper(typeof(Startup));

然后,在AutoMapperProfile.cs中:

public class AutomapperProfile : Profile
{
    public AutomapperProfile()
    {
        // This is not working:
        CreateMap<ApplicationRoleViewModel, SelectableRoleViewModel>()
            .ForMember(dest => dest.Selected, i => i.Ignore());

        // This is working:
        CreateMap<ApplicationUser, ApplicationUserViewModel>();

        // Many more mappings, all working
    }
}

我怎样才能让它工作?

您指定的代码似乎是正确的。

我只建议删除具有相同名称的属性的 ForMember 方法,因为自动映射器会自动处理它:

CreateMap<ApplicationRoleViewModel, SelectableRoleViewModel>()
    .ForMember(dest => dest.Selected, i => i.Ignore());

问题似乎是因为您没有正确使用映射器。你在哪里注册映射器?注册是在地图之前进行的吗?你是在启动时做的吗?如果您指定更多代码,将更容易提供帮助。

更新:

获得更多代码和信息后,问题是地图在不同的对象上工作,ApplicationRoleViewModel 而不是 ApplicationRole

只是为了看看区别 ;)

public static SelectableRoleViewModel ToSelectable(this ApplicationRoleViewModel model)
{
    return new SelectableRoleViewModel 
    {
       Id = model.Id,
       DisplayName = model.DisplayName
    };
}

// Usage
var selectable = applicationRole.ToSelectable();
  • 输入一次
  • 完全可测试
  • 完全可维护 - 支持各种 conversion/mapping
  • 减少注入的依赖项和抽象(映射器)的数量
  • 没有对第三方库的额外依赖