将实体框架中存储过程中的返回数据强制转换为listviewmodel

本文关键字:数据 转换 listviewmodel 返回 框架 实体 存储 过程中 存储过程 | 更新日期: 2023-09-27 17:54:45

这是我的ViewModel:

public class CarViewModel
{
    public string Registration { get; set; }
    public string ModelName { get; set; }
    public string Colour { get; set; }
    public DateTime Year { get; set; }
}

我的代码

  [HttpGet]
  public ActionResult GetAllCars()
  {
        CarRentalEntities entities = new CarRentalEntities();
        List<CarViewModel> carsViewModel = new List<CarViewModel>();
        var cars = entities.GetAllCars();    
        // Is it possible to convert cars to carsViewModel Collection and 
        //return it to the view ????????????????
        return View(carsViewModel); 
  }

这是我的SQL存储过程,由实体框架调用

Create Procedure  GetAllCars
as
(
    Select 
       c.registration, m.model_name, c.colour, m.model_year
    from 
       Cars c 
    inner join 
       models m on c.model_id = m.model_id
)

在我的实体框架代码中,我想做的就是将类型为System.Data.Entity.Core.Object.ObjectResults<GetAllCars_Result>的存储过程GetAllCars返回的集合转换为类型的集合List<CarViewModel>

如何做到这一点?我找不到合适的教程或文章。

Thank you

将实体框架中存储过程中的返回数据强制转换为listviewmodel

  [HttpGet]
  public ActionResult GetAllCars()
  {
        CarRentalEntities entities = new CarRentalEntities();
        var cars = entities.GetAllCars();    
        List<CarViewModel> carsViewModel = cars.Select(c=> new CarViewModel
        {
         Registration = c.Registration,
         // and so on
        }).ToList();
        return View(carsViewModel); 
  }

您可以使用Linq select方法对枚举进行转换。

So list =

cars.Select(c=>new viewmodel()  { 
    //initialize params here
});