使用 Automapper 将模型传递给 ViewModel

我正在从事 ASP.NET 核心项目。我想使用 Automapper 将模型映射到视图模型,但是存在下面描述的问题 This is MyRepository


 public class MyRepository

 {

     public async Task<IEnumerable<Cars>> GetAllCarsAsync()

    {

        return await _RepositoryContext.Set<Cars>().ToListAsync();

    }

 }

这是我的控制器


 public class MyController: Controller

 {

    [HttpGET]

    public async Task<IActionResult> Create()

      {

          var car = await _MyRepository.GetAllCarTypesAsync();

          var model = _mapper.Map<IEnumerable<CarsVM>>(car);

          return View(model);

      }

 }

最后这是我的观点


@model  DataLayers.Models.ViewModels.CarsVM


<form " asp-controller="MyController" asp-action="Create">

  <label class="label" asp-for="Carname"></label>

  <input class="input" type="text" asp-for="Carname">

  <select>

     <option> A carType </option>

     <option>A carType </option>

  </select>

</from>

问题出在我的控制器上。var car 返回 IEnumerable,然后我们将结果映射到 CarsVM。当我传递模型进行查看时,它期望 CarsVM 而不是 CarsVM 的 IEnumerable。我怎样才能隐藏它们?如果现在可以转换它们,那我该怎么办?如何传递我的数据以供查看?


ITMISS
浏览 77回答 1
1回答

跃然一笑

我建议更新 automapper 行以转换为 List 而不是 IEnumerable 接口,以便您可以确保视图模型在控制器中具体化。查看存储库代码很明显,但如果您只能看到存储库返回 IEnumerable,则不是。下面的主要更改是确保 AutoMapper 映射到视图模型对象列表,并且视图正在接收由这些视图模型对象列表组成的模型。我假设 CarsVM 对象是单个 Cars 对象的视图模型实例。资料库public class MyRepository{&nbsp; &nbsp; public async Task<List<Cars>> GetAllCarsAsync()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return await _RepositoryContext.Set<Cars>().ToListAsync();&nbsp; &nbsp; }}控制器public class MyController: Controller{&nbsp; &nbsp; [HttpGET]&nbsp; &nbsp; public async Task<IActionResult> Create()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var car = await _MyRepository.GetAllCarTypesAsync();&nbsp; &nbsp; &nbsp; &nbsp; var model = _mapper.Map<List<CarsVM>>(car);&nbsp; &nbsp; &nbsp; &nbsp; return View(model);&nbsp; &nbsp; }}看法@model List<DataLayers.Models.ViewModels.CarsVM><form asp-controller="MyController" asp-action="Create">&nbsp; &nbsp; <label class="label" asp-for="Carname"></label>&nbsp; &nbsp; <input class="input" type="text" asp-for="Carname">&nbsp; &nbsp; <select>&nbsp; &nbsp; &nbsp; &nbsp;<option> A carType </option>&nbsp; &nbsp; &nbsp; &nbsp;<option>A carType </option>&nbsp; &nbsp; </select></from>
打开App,查看更多内容
随时随地看视频慕课网APP