[英]Passing entity framework query to view error
我剛剛使用實體框架代碼優先方法創建了一個數據庫。
這是我的模態課
public class MobileProduct
{
[Key]
public int p_id { get; set; }
public string p_name { get; set; }
public string p_description { get; set; }
public string p_price { get; set; }
}
這是我的DbContext派生類
public class Entities : DbContext
{
public DbSet<MobileProduct> Mobiles { get; set; }
}
我剛剛創建了一個查詢,以通過操作方法傳遞此數據視圖
Entities db = new Entities();
public ActionResult Mobiles()
{
var q = from n in db.Mobiles
select n;
return View(q);
}
這是我的看法
@model HomeShopping.Models.MobileProduct
@{
ViewBag.Title = "Mobiles";
}
<h2>Mobiles</h2>
訪問視圖時出現錯誤 :
傳遞到字典中的模型項的類型為'System.Data.Entity.Infrastructure.DbQuery`1 [HomeShopping.Models.MobileProduct]',但是此字典需要類型為'HomeShopping.Models.MobileProduct'的模型項。
說明:執行當前Web請求期間發生未處理的異常。 請查看堆棧跟蹤,以獲取有關錯誤及其在代碼中起源的更多信息。
異常詳細信息:System.InvalidOperationException:傳遞到字典中的模型項的類型為“ System.Data.Entity.Infrastructure.DbQuery`1 [HomeShopping.Models.MobileProduct]”,但是此字典需要模型項為“ HomeShopping”。 Models.MobileProduct”。
我假設您要向視圖發送MobileProduct列表? 如果是這樣的話; 將您的模型更改為
@model IEnumerable<HomeShopping.Models.MobileProduct>
@{
ViewBag.Title = "Mobiles";
}
<h2>Mobiles</h2>
當前,您的模型僅需要一個MobileProduct類型的實例,而您的Mobiles操作正在創建MobileProduct的列表。 您還需要通過對操作執行ToList()來評估該操作中的查詢。
public ActionResult Mobiles()
{
var q = from n in db.Mobiles
select n;
return View(q.ToList());
}
您沒有實現查詢,因此將查詢本身(而不是查詢結果)發送到視圖。
var q = (from n in db.Mobiles
select n).ToList();
return View(q);
正如daveL發布的那樣,您還需要在視圖中更改模型的定義。
@model IEnumerable<HomeShopping.Models.MobileProduct>
尚未測試,但嘗試將模型定義為:
@model IQuerable<HomeShopping.Models.MobileProduct>
如果那不起作用,那么也許:
@model IEnunerable<HomeShopping.Models.MobileProduct>
...對象返回為:
View(q.ToList());
您將查詢保存到q,而不是查詢的評估。 如果期望多個結果,則需要一個ToList()。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.