将异步模型集映射到异步ViewModel集合
我正在使用一个项目,我需要使用Async编程C#。 我在Model和ViewModel之间使用Automapper进行映射。 对于异步数据,我创建了一个map方法,如下所示:
public static async Task<IEnumerable> ModelToViewModelCollectionAsync(this Task<IEnumerable> persons) { return await Mapper.Map<Task<IEnumerable>, Task<IEnumerable>>(persons); }
我将此映射方法称为如下(在我的服务类中):
public async Task<IEnumerable> GetAllAsync() { return await _personRepository.GetAllAsync("DisplayAll").ModelToViewModelCollectionAsync(); }
最后我在控制器内调用了我的服务类。
public async Task Index() { return View(await PersonFacade.GetAllAsync()); }
但是当我运行我的项目时,它会向我显示以下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]]
根据我的项目架构,它不可能避免自动化。
注意:我的getall存储库方法如下:
public virtual async Task<IEnumerable> GetAllAsync(string storedProcedure) { return await _conn.QueryAsync(storedProcedure); }
解决了这个问题。 我在这里应用了一点点技巧。 我没有在服务层创建Async的扩展方法,而是编写了如下代码:
public async Task> GetAllAsync() { var persons = await _personRepository.GetAllAsync("DisplayAll"); var personList = PersonExtension.ModelToViewModelCollection(persons); return personList; }
剩下的都没有变化。
现在它工作正常。