Automapper 5.0全局配置

我在App_Start文件夹中的AutoMapperConfig.cs中使用下面的代码。 我在Global.asax中将其初始化为AutoMapperConfiguration.Configure()

但我无法在我的控制器中使用Mapper.Map 。 它抛出的exception是没有定义映射。 它在以前版本的Mapper.CreateMap中工作,它支持Mapper.CreateMap方法。 我很困惑如何使用MapperConfiguration实例。

 public static class AutoMapperConfiguration { public static void Configure() { Mapper.Initialize( cfg => { cfg.AddProfile(); } ); Mapper.AssertConfigurationIsValid(); } } public class HospitalProfile : Profile { protected override void Configure() { var config = new MapperConfiguration( cfg => { cfg.CreateMap() .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id.ToString())); }); config.CreateMapper(); } } 

尝试访问此地图,如下所示

 Mapper.Map<IEnumerable, IEnumerable>(hospitalsOnDB); 

在这种情况下,您确实需要使用配置文件吗? 如果你不这样做,你可以尝试像这样初始化Mapper:

 public static class AutoMapperConfiguration { public static void Configure() { Mapper.Initialize( config => { config.CreateMap() .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id.ToString())); }); } } 

但是,如果您仍想注册个人资料,可以执行以下操作:

 public static class AutoMapperConfiguration { public static void Configure() { Mapper.Initialize( cfg => { cfg.AddProfile(); } ); } } public class HospitalProfile : Profile { protected override void Configure() { CreateMap() .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id.ToString())); } } 

希望这可以帮助。 如果您使用的是AutoMapper 5.0,请记住此时此时仍处于测试阶段。

您可以在AutoMapper 5.2中使用它。

您的个人资料类如下

 public class MapperProfile: Profile { public MapperProfile() { CreateMap().ReverseMap(); } } 

然后在你的Global.asax中

  protected void Application_Start() { //Rest of the code Mapper.Initialize(c => c.AddProfiles(new string[] { "DLL NAME OF YOUR PROFILE CLASS" })); } 

现在需要创建实例时

 AutoMapper.Mapper.Instance.Map(source, new Hospital()); 

希望这可以帮助。