2017-07-18 183 views
2

當我嘗試使用automapper映射在運行時生成的類。Automapper - 動態類型映射

AssemblyName asmName = new AssemblyName(string.Format("{0}_{1}", "tmpAsm", Guid.NewGuid().ToString("N"))); 
AssemblyBuilder asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run); 
ModuleBuilder moduleBuilder = asmBuilder.DefineDynamicModule("core"); 
TypeBuilder typeBuilder = GetTempModule().DefineType("MyDynamicClass", TypeAttributes.Public); 
Type proxy = typeBuilder.CreateType(); 
var mc = new MapperConfiguration(cfg => 
{ 
    cfg.CreateMap(proxy, typeof(MyViewModel)); 
}); 

var mapper = mc.CreateMapper(); 
mapper.Map<MyViewModel>(Activator.CreateInstance(proxy)); 

我得到以下錯誤:

AutoMapper.AutoMapperMappingException : Missing type map configuration or unsupported mapping.

儘管錯誤消息說的話,映射已經decleared,你可以看到。任何建議?

+0

測試是沒有什麼更多的異常消息(通常說明它缺少哪個映射,基本上是在哪些類之間) –

回答

0

嘗試使用:

TypeBuilder typeBuilder = moduleBuilder.DefineType("MyDynamicClass", TypeAttributes.Public); 

相反的:

TypeBuilder typeBuilder = GetTempModule().DefineType("MyDynamicClass", TypeAttributes.Public); 

此外,檢查您正在使用的AutoMapper的版本:我在6.1.1.0