I am using the code below in AutoMapperConfig.cs
in App_Start
folder. I initialized it in Global.asax
as AutoMapperConfiguration.Configure()
But I am unable to use the Mapper.Map<Hospital, MongoHospital>
in my controller. It is throwing an exception that no mappings are defined. It was working in previous versions of Automapper which were supporting Mapper.CreateMap<>
methods. I am confused how to use MapperConfiguration
instance.
public static class AutoMapperConfiguration
{
public static void Configure()
{
Mapper.Initialize(
cfg =>
{
cfg.AddProfile<HospitalProfile>();
}
);
Mapper.AssertConfigurationIsValid();
}
}
public class HospitalProfile : Profile
{
protected override void Configure()
{
var config = new MapperConfiguration(
cfg =>
{
cfg.CreateMap<Hospital, MongoHospital>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id.ToString()));
});
config.CreateMapper();
}
}
Trying to access this map as below
Mapper.Map<IEnumerable<Hospital>, IEnumerable<MongoHospital>>(hospitalsOnDB);
Do you actually need to use a Profile in this scenario? If you don't, you can try just initialising the Mapper like this:
public static class AutoMapperConfiguration
{
public static void Configure()
{
Mapper.Initialize(
config =>
{
config.CreateMap<Hospital, MongoHospital>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id.ToString()));
});
}
}
However, if you would like to still register a Profile, you can do this:
public static class AutoMapperConfiguration
{
public static void Configure()
{
Mapper.Initialize(
cfg =>
{
cfg.AddProfile<HospitalProfile>();
}
);
}
}
public class HospitalProfile : Profile
{
protected override void Configure()
{
CreateMap<Hospital, MongoHospital>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id.ToString()));
}
}
Hope this helps. If you're using AutoMapper 5.0, remember that this is still at beta-1 at this point in time.
You can use this with AutoMapper 5.2.
Your Profile class as below
public class MapperProfile: Profile
{
public MapperProfile()
{
CreateMap<Hospital, MongoHospital>().ReverseMap();
}
}
Then in your Global.asax
protected void Application_Start()
{
//Rest of the code
Mapper.Initialize(c => c.AddProfiles(new string[] { "DLL NAME OF YOUR PROFILE CLASS" }));
}
Now when you need to create an instance
AutoMapper.Mapper.Instance.Map<MongoHospital, Hospital>(source, new Hospital());
Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.