我想从我的 Controller 传递数据来查看。 这是 Controller 的代码
public ActionResult AllCars()
{
try
{
int id = System.Web.HttpContext.Current.User.Identity.GetUserId<int>();
var reservedCars = (from c in db.Cars
join o in db.Orders on c.Car_Id equals o.Car_Id
join u in db.AspNetUsers on o.Id equals u.Id
where u.Id == 5
select new
{
c.Car_Description,
c.Car_Id,
c.CarMakeId,
c.CarModelId,
c.Reservation_Status,
c.Color
});
return View(reservedCars);
}
catch (Exception)
{
throw;
}
}
这是我的 View 文件。
@model IEnumerable<FinalProject.Models.ReservedCar>
<table>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Car_Id);
</td>
</tr>
}
</table>
但是当我运行 View 时出现以下错误 传递到字典中的模型项的类型为“System.Data.Entity.Infrastruct.DbQuery”,但此字典需要类型为“System.Collections.IEnumerable”的模型项
我知道我正在将 dbquery 结果传递给 View ,并且我的 View 期望它将是 iEnumerable。 请指导我如何完成这项任务。?我只是想将查询结果传递到我的 View 中并想使用它。
模型类。 保留汽车.cs
namespace FinalProject.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
public partial class ReservedCar
{
public int Id { get; set; }
public string Car_Description { get; set; }
public int Car_Id { get; set; }
public string CarMakeId { get; set; }
public string CarModelId { get; set; }
public string Reservation_Status { get; set; }
public string Color { get; set; }
}
}
最佳答案
目前reservedCars
仍然是 IQueryable
类型的查询表达式。它尚未被评估/执行。所以类型为reservedCars
与您的 View 强类型化的类型不同( IEnumerable<ReservedCar>
)。这就是您收到类型不匹配错误的原因。
确保您返回的是 ReservedCar
的集合类(class)。您可以更新 LINQ 表达式的投影部分,将结果投影到 ReservedCar
而不是匿名对象。也可调用ToList()
查询上的方法将执行查询表达式并返回结果。
var reservedCars = (from c in db.Cars
join o in db.Orders on c.Car_Id equals o.Car_Id
join u in db.AspNetUsers on o.Id equals u.Id
where u.Id == 5
select new ReservedCarVm
{
CarId = c.Car_Id,
Description = c.Car_Description,
Color = c.Color
// Map other properties as needed.
}).ToList();
return View(reserverCars);
假设您的ReservedCarVm
类(class)有Color
, Car_Description
和Car_Id
与 Car
中的属性具有相同类型的属性实体类如下所示
public class ReservedCarVm
{
public string Color { set;get;}
public string Description { set;get;}
//Add other properties needed by the view here
}
现在确保您的 View 强类型化到此 View 模型类的集合
@model IEnumerable<ReserverdCarVm>
@foreach(var item in Model)
{
<p>@item.CarId</p>
<p>@item.Color</p>
}
关于c# - 如何传递自定义查询结果以在asp.net中查看,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39056364/