2016-11-22 209 views
0

.NET框架4.5.2,.Asp.NET網頁API 5.2.3,5.1.1 AutoMapperMapper.Map <任務<IEnumerable的<Address>>,任務<IEnumerable的<AddressView>>()

我有以下ASP地址控制器上的.NET MVC WebApi操作方法。對於我的測試,我只返回10條記錄,你可以在下面的服務的方法,請參閱:

[Route("api/Address/GetAllAsync")] 
[HttpGet] 
public async Task<IEnumerable<AddressModel>> GetAllAsync() 
{ 
    AddressService service = new AddressService(new DataContext()); 
    Task<IEnumerable<Address>> data = service.GetAllAddressesAsync(); 
    var addressList = Mapper.Map<Task<IEnumerable<Address>>, Task<IEnumerable<AddressModel>>>(data); 

    return await addressList; 
} 

service.GetAllAddressesAsync是

public async Task<IEnumerable<Address>> GetAlladdressesAsync() 
{ 
    var data = from a in _context.Addresses.Take(10) 
       orderby a.City 
       select a; 

    return await data.ToListAsync(); 
} 

AutoMapper在Global.asax.cs中配置爲:

Mapper.Initialize(cfg => cfg.CreateMap<Address, AddressModel>()); 
Mapper.AssertConfigurationIsValid(); 

我也嘗試配置AutoMapper像

Mapper.Initialize(cfg => cfg.CreateMap<Task<IEnumerable<Address>>, Task<IEnumerable<AddressModel>>>()); 
Mapper.AssertConfigurationIsValid(); 

第一次配置解決方案啓動,但從瀏覽器調用GetAllAsync()方法時,響應正文(在F12 Developer Tools/Networking中)顯示以下錯誤消息:

{「message」:「發生。「,」exceptionMessage「:」缺少類型映射配置或不支持映射。\ r \ n \ r \ n映射類型:\ r \ n任務1 -> Task 1 \ r \ nSystem.Threading.Tasks.Task 1[[System.Collections.Generic.IEnumerable 1 [[DataAccess.Address ,DataAccess,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null]],mscorlib,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089]] - > System.Threading.Tasks.Task 1[[System.Collections.Generic.IEnumerable 1 [[TestAspNetIdentity .Models.AddressModel,TestAspNetIdentity,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null]],mscorlib,Version = 4.0.0.0,Culture = neutral, PublicKeyToken =「b77a5c561934e089」]「,」exceptionType「:」AutoMapper.AutoMapperMappingException「,」stackTrace「:」

當嘗試AutoMapper的第二個配置時,解決方案啓動,但調用方法時,請求死亡,沒有任何響應或異常客戶端或服務器上,並且瀏覽器在無限循環中等待響應。

我應該如何配置和使用AutoMapper來將Task<IEnumerable<MyTypeA>>映射到Task<IEnumerable<MyTypeB>>?我是否使用async-task-awayt用法做出一些基本的錯誤?有人有一個例子嗎? 謝謝你的幫助。

問候 阿德里安

回答

2

你不應該試圖映射一個任務 - 等待任務的結果,映射的是:

[Route("api/Address/GetAllAsync")] 
[HttpGet] 
public async Task<IEnumerable<AddressModel>> GetAllAsync() 
{ 
    AddressService service = new AddressService(new DataContext()); 
    IEnumerable<Address> data = await service.GetAllAddressesAsync(); 
    var addressList = Mapper.Map<IEnumerable<AddressModel>>(data); 

    return addressList; 
} 

而且,你不需要指定源類型映射時。

相關問題