使用自动映射器映射异步结果 [英] Map async result with automapper
问题描述
我们正在创建一个angularjs应用程序的Web.Api应用程序. Web.Api返回json结果.
We are createing a Web.Api application of a angularjs application. The Web.Api returns a json result.
第一步是获取数据:
public List<DataItem>> GetData()
{
return Mapper.Map<List<DataItem>>(dataRepository.GetData());
}
那就像一个魅力.然后,我们使数据存储异步,并更改为使用它的代码.
That worked like a charm. Then we made the data repo async and we changed to code to work with it.
public List<DataItem>> GetData()
{
return Mapper.Map<List<DataItem>>(dataRepository.GetDataAsync().Result);
}
仍然没有问题.现在我们要使Web.Api完全异步,所以我们将其更改为:
Stil no problems. Now we wanted to make my Web.Api full async awayt so we changed it to:
public async Task<List<DataItem>> GetData()
{
return await Mapper.Map<Task<List<DataItem>>>(dataRepository.GetDataAsync());
}
此时,Automapper感到困惑.首先,我们有以下映射规则: Mapper.CreateMap();
At this moment Automapper gets confused. First we had the following mapper rule: Mapper.CreateMap();
这一直有效,直到Web api方法变得完全异步为止.例外情况是,它缺少
This worked until the web api method became full async. The exception said it was missing a map from
Task<ICollection<Data>> to Task<ICollection<DataItem>>.
映射器已更改为
Mapper.CreateMap<Task<List<Data>>, Task<List<DataItem>>>();
在验证配置时,它抱怨无法映射结果.我们应该如何配置映射?
When validating the configuration it complains that Result cannot be mapped. How should we configure the mappings?
推荐答案
您需要将获取的异步数据移出Map调用:
You need to move the async data fetch out of the Map call:
var data = await dataRepository.GetDataAsync();
return Mapper.Map<List<DataItem>>(data);
或者,您可以使用AutoMapper LINQ投影:
Alternatively, you can use AutoMapper LINQ projections:
var data = await dbContext.Data.ProjectTo<DataItem>().ToListAsync();
我不知道您的存储库是否直接公开IQueryable(我们不使用存储库).这些天,我们的应用几乎只使用第二个版本.
I don't know if your repository exposes IQueryable directly (we don't use repositories). Our apps use the second version pretty much exclusively these days.
这篇关于使用自动映射器映射异步结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!