序列不包含元素错误 - MVC(模型和数据访问)
Posted
技术标签:
【中文标题】序列不包含元素错误 - MVC(模型和数据访问)【英文标题】:Sequence contains no elements errror - MVC (Models and Data Access) 【发布时间】:2014-02-12 09:57:18 【问题描述】:我正在尝试关注 MVC Music Store tutorial ,但我遇到了一个我无法处理的错误。我已经创建了动作:
public ActionResult Browse(string category)
using (OnlineStoreDbContext db = new OnlineStoreDbContext())
// Get category and its associated products
var categoryModel = db.Categories.Include("Products")
.Single(c => c.Title == category);
return View(categoryModel);
比我创建的和各自的视图:
@model OnlineStoreMVC.Core.Models.Category
@
ViewBag.Title = "Browse";
<h2>Browse Category: @Model.Title</h2>
<ul>
@foreach (var product in Model.Products)
<li>
@product.Title
</li>
</ul>
但是当我尝试打开:http://localhost:51642/Store/Browse?cat=Action
时,出现错误:
"Sequence contains no elements"
关于这一行:
var categoryModel = db.Categories.Include("Products")
.Single(c => c.Title == category);
我已经尝试用 SingleOrDefault 替换 Single,但是错误是
"Object reference not set to an instance of an object."
关于视图中的那一行:"<h2>Browse Category: @Model.Title</h2>"
【问题讨论】:
“类别”的价值是什么?用调试检查。 【参考方案1】:问题是您将 cat 作为您的 url 中的键传递,它应该是类别。所以你应该打电话给http://localhost:51642/Store/Browse?category=Action
关于“对象引用未设置为对象的实例”错误,您必须将 Action 方法更改为:
public ActionResult Browse(string category)
using (OnlineStoreDbContext db = new OnlineStoreDbContext())
// Get category and its associated products
var categoryModel = db.Categories.Include("Products")
.SingleOrDefault(c => c.Title == category);
if (categoryModel == default(Category))
categoryModel = new Category();
categoryModel.Products = new List<Product>();
return View(categoryModel);
【讨论】:
以上是关于序列不包含元素错误 - MVC(模型和数据访问)的主要内容,如果未能解决你的问题,请参考以下文章