使用自动映射器映射异步结果

编程入门 行业动态 更新时间:2024-10-27 11:22:09
本文介绍了使用自动映射器映射异步结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我们正在创建一个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.

更多推荐

使用自动映射器映射异步结果

本文发布于:2023-11-04 12:06:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1557891.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:映射器

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!