報錯:Missing type map configuration or unsupported mapping
□ 背景
當把View Model轉換成Domain Model儲存的時候,發生在AutoMapper的錯誤。
□ 分析
1、在派生於AutoMapper的Profile的類中已經建立對映:
Mapper.CreateMap<SomeDomainModel, SomeViewModel>();
2、也已經初始化派生於Profile的類:
public static class AutoMapperConfiguration
{
public static void Configure()
{
Mapper.Initialize(x => x.AddProfile<SomeProfile>());
}
}
3、在全域性中也註冊了:
protected void Application_Start()
{
//配置對映
AutoMapperConfiguration.Configure();
}
4、單元測試也通過:
[TestClass]
public class AutoMapperConfigurationTester
{
[TestMethod]
public void TestMethod1()
{
AutoMapperConfiguration.Configure();
Mapper.AssertConfigurationIsValid();
}
}
□ 解決方法
在實際對映的時候,把AutoMapper.Mapper.Map<Source, Destination>換成AutoMapper.Mapper.DynamicMap<Source, Destination>
DomainModel someDomainModel = AutoMapper.Mapper.Map<ViewModel, DomainModel>(someViewModel);
改成:
DomainModel someDomainModel = AutoMapper.Mapper.DynamicMap<ViewModel, DomainModel>(someViewModel);