[英]Automapper 5.0 global configuration
我在App_Start
文件夾的AutoMapperConfig.cs
中使用以下代碼。 我在Global.asax
中將其初始化為AutoMapperConfiguration.Configure()
但是我無法在我的控制器中使用Mapper.Map<Hospital, MongoHospital>
。 沒有定義任何映射是一個例外。 它在支持Mapper.CreateMap<>
方法的Mapper.CreateMap<>
版本的Mapper.CreateMap<>
。 我很困惑如何使用MapperConfiguration
實例。
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();
}
}
嘗試按以下方式訪問此地圖
Mapper.Map<IEnumerable<Hospital>, IEnumerable<MongoHospital>>(hospitalsOnDB);
在這種情況下,您是否真的需要使用配置文件? 如果不這樣做,可以嘗試像這樣初始化Mapper:
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()));
});
}
}
但是,如果您仍要注冊個人資料,則可以執行以下操作:
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()));
}
}
希望這可以幫助。 如果您使用的是AutoMapper 5.0,請記住,此時它仍處於beta-1狀態。
您可以在AutoMapper 5.2中使用它。
您的個人資料類別如下
public class MapperProfile: Profile
{
public MapperProfile()
{
CreateMap<Hospital, MongoHospital>().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<MongoHospital, Hospital>(source, new Hospital());
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.