我想从我的db中获取记录,其中hidden = false并且在浏览器中获取了id。请看我的代码并为我修复,非常感谢(我搜索但无法修复我的错误)。 我的行动:
public ActionResult Detail(int id = 0)
{
var item = db.Destinations.Where(i=>i.Hidden==false && i.Id==id);
if (item==null)
{
return HttpNotFound();
}
return View(item);
}
我的观点:
@model vtt.Models.Destination
@{
ViewBag.Title = "Detail";
}
<div class="white">
<h1>@Model.Name</h1>
@Html.Raw(Model.Description)
</div>
错误:
The model item passed into the dictionary is of type
'System.Data.Entity.Infrastructure.DbQuery`1[vtt.Models.Destination]', but this dictionary
requires a model item of type 'vtt.Models.Destination'.
答案 0 :(得分:3)
目前,您正在尝试传入一个查询的模型,而您的视图需要一个单个模型对象。目前,您对无效性的检查也毫无意义 - Where
的结果永远不会是null
......这只是一个查询。
相反,您应该使用SingleOrDefault
,*执行查询,获取单个值:
var item = db.Destinations.SingleOrDefault(i => !i.Hidden && i.Id == id);
现在检查无效将非常有用(因为如果没有结果,SingleOrDefault
将返回null
)并且视图的类型将是正确的。