将返回的数据从实体框架中的存储过程投射到列表

问题描述 投票:4回答:2

这里是我的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
)

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

如何实现?我找不到合适的教程或文章。

谢谢

c# .net entity-framework lambda linq-to-entities
2个回答
4
投票
  [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); 
  }

1
投票

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

所以列表=

cars.Select(c=>new viewmodel()  { 
    //initialize params here
});
© www.soinside.com 2019 - 2024. All rights reserved.