如何配置和使用automapper 5.1.1

时间:2016-11-09 23:32:16

标签: asp.net-core automapper-5

我一直在关注this,试图弄清楚如何使AutoMapper工作。这就是我之前的事情

public class DomainToViewModelMappingProfile: Profile
{
    public DomainToViewModelMappingProfile()
    {
        Mapper.Initialize(cfg => cfg.CreateMap<Institution, InstitutionDataViewModel>()
        .ForMember(vm => vm.InstitutionID, map => map.MapFrom(s => s.InstitutionID))
        .ForMember(vm=>vm.InstituteName,map=>map.MapFrom(s=>s.InstituteName))
        .ForMember(vm=>vm.Circuit,map=>map.MapFrom(s=>s.AdministrativeStructure.AdminStructName))
        .ForMember(vm=>vm.Level,map=>map.MapFrom(s=>s.Level.LevelName))
        );
    }
}

然后是

 public class AutoMapperConfiguration
{
    public static void Configure()
    {
        Mapper.Initialize(x =>
        {
            x.AddProfile<DomainToViewModelMappingProfile>();
        });
    }
}

最后我在startup.cs

中有这个
// Automapper Configuration
        AutoMapperConfiguration.Configure();

我现在的困难是如何让我的控制器工作,以及我是否在正确的轨道上。随着所有不同的信息和不同的方法到处都是我非常困惑 提前致谢

1 个答案:

答案 0 :(得分:1)

您的个人资料需要调用非静态方法。将其从Mapper.CreateMap...更改为简单:

public class DomainToViewModelMappingProfile : Profile
{
    public DomainToViewModelMappingProfile()
    {
        CreateMap<Institution, InstitutionDataViewModel>()
        .ForMember(vm => vm.InstitutionID, map => map.MapFrom(s => s.InstitutionID))
        .ForMember(vm => vm.InstituteName, map => map.MapFrom(s => s.InstituteName))
        .ForMember(vm => vm.Circuit, map => map.MapFrom(s => s.AdministrativeStructure.AdminStructName))
        .ForMember(vm => vm.Level, map => map.MapFrom(s => s.Level.LevelName))
        );
    }
}