gpt4 book ai didi

c# - 将返回的数据从 Entity Framework 中的存储过程转换为 List

转载 作者:太空狗 更新时间:2023-10-30 01:04:35 25 4
gpt4 key购买 nike

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

这是由 Entity Framework 调用的我的 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> .

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

谢谢

最佳答案

  [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);
}

关于c# - 将返回的数据从 Entity Framework 中的存储过程转换为 List<ViewModel>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22735696/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com