【问题标题】:Map Async Model Collection to Async ViewModel Collection将异步模型集合映射到异步 ViewModel 集合
【发布时间】:2014-07-18 14:28:29
【问题描述】:

我正在处理一个需要使用异步编程 C# 的项目。我正在使用 Automapper 在 Model 和 ViewModel 之间进行映射。对于异步数据,我创建了一个 map 方法,如下所示:

public static async Task<IEnumerable<PersonView>> ModelToViewModelCollectionAsync(this Task<IEnumerable<Person>> persons)
{
    return await Mapper.Map<Task<IEnumerable<Person>>, Task<IEnumerable<PersonView>>>(persons);
}

我将这个映射方法称为如下(在我的服务类中):

public async Task<IEnumerable<PersonView>> GetAllAsync()
{
    return await _personRepository.GetAllAsync("DisplayAll").ModelToViewModelCollectionAsync();
}

最后我在控制器中调用了我的服务类。

public async Task<ActionResult> Index()
{
    return View(await PersonFacade.GetAllAsync());
}

但是当我运行我的项目时,它会显示以下异常

Missing type map configuration or unsupported mapping.

Mapping types:
Task`1 -> Task`1
System.Threading.Tasks.Task`1[[System.Collections.Generic.IEnumerable`1[[PF.Model.Person, PF.Model, 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[[PF.Services.ViewModel.PersonView, PF.Services, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]

Destination path:
Task`1

Source value:
System.Threading.Tasks.Task`1[System.Collections.Generic.IEnumerable`1[PF.Model.Person]]

根据我的项目架构,不可能避免自动映射器。

注意:我的getall存储方法如下:

public virtual async Task<IEnumerable<T>> GetAllAsync(string storedProcedure)
{
    return await _conn.QueryAsync<T>(storedProcedure);
}

【问题讨论】:

    标签: c# asp.net-mvc asynchronous domain-driven-design automapper


    【解决方案1】:

    解决了这个问题。我在这里应用了一些小技巧。我没有在服务层中为异步创建扩展方法,而是编写了如下代码:

    public async Task<IEnumerable<PersonView>> GetAllAsync()
            {
                var persons = await _personRepository.GetAllAsync("DisplayAll");
                var personList = PersonExtension.ModelToViewModelCollection(persons);
                return personList;
            }
    

    其余全部不变。

    现在可以正常使用了。

    【讨论】:

      猜你喜欢
      • 2021-10-22
      • 1970-01-01
      • 2014-05-10
      • 1970-01-01
      • 1970-01-01
      • 2011-07-12
      • 2017-04-20
      • 2021-12-09
      • 2018-01-28
      相关资源
      最近更新 更多