Map Async Model Collection to Async ViewModel Coll

2019-03-21 16:58发布

问题:

I am working with a project where I need to work with Async programming C#. I am using Automapper for map between Model and ViewModel. For Async data I created a map method as follows:

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

And I called this mapping method as follows (In my service class):

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

Finally I called my service class inside controller.

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

But when I run my project it shows me following exception

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]]

According to my project architecture its not possible to avoid automapper.

Note: My repository method for getall is as follows:

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

回答1:

Solved this issue. I applied little bit trick here. Instead of creating extension method for Async in service layer I wrote my code as follows:

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

remaining all are unchanged.

now it work fine.