【发布时间】:2014-12-03 01:39:02
【问题描述】:
我正在尝试从数据库中检索数据并写出记录,但出现错误:
An exception of type 'System.NullReferenceException' occurred in App_Web_uaarpxja.dll but was not handled in user code
Additional information: Object reference not set to an instance of an object.
数据库模型PastaModel.cs
public class Item
{
[Key]
public int Itemid { get; set; }
public string Itemname { get; set; }
public int Itemprice { get; set; }
public int Currentstock { get; set; }
public string Itemtype { get; set; }
public string pictureURL { get; set; }
}
public class PastaContext : DbContext
{
public PastaContext()
: base("name=PastaModel")
{
Database.CreateIfNotExists();
}
public DbSet<Item> Items { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
控制器 ItemController.cs
public class ItemController : Controller
{
private PastaContext db = new PastaContext();
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index()
{
return View();
}
}
查看Index.cshtml
@model IEnumerable<Oblig1.Models.Item>
<!DOCTYPE html>
<br />
<br />
<html>
<head>
<title>Index</title>
</head>
<body>
@foreach (var item in Model)
{
<p>@item.Itemname</p>
}
</body>
</html>
我在@foreach (var item in Model) {这一行收到此错误
编辑:添加 DbContext
【问题讨论】:
标签: c# asp.net-mvc web-applications model-view-controller foreach