用于对象引用的MVC 4错误

时间:2015-02-09 12:24:03

标签: c# asp.net-mvc object model-view-controller reference

这是型号:

[Table("Person")]
public class Persons
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Gender { get; set; }
    public string Location { get; set; }
}

对于上述模型类,这是我的DbContext

public class PersonContext : DbContext
{
    public DbSet<Persons> persons { get; set; }
}

这是我的控制器类:

public class PersonController : Controller
{
    //
    // GET: /Person/
    public ActionResult Index(int id)
    {
        PersonContext PC = new PersonContext();
        Persons PS = PC.persons.SingleOrDefault(pr => pr.ID == id);
        return View(PS);
    }
}

这是我的观点:

'@model MVCDemo.Models.Persons

@{
ViewBag.Title = "Index";
Layout = "~/Views/_ViewStart.cshtml";
}

<h2>Index</h2>

<div>
<h4>Personal Information</h4>
<hr />
<dl class="dl-horizontal">
    <dt>
        @Html.DisplayNameFor(model => model.Name)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.Name)
    </dd>

    <dt>
        @Html.DisplayNameFor(model => model.Gender)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.Gender)
    </dd>

    <dt>
        @Html.DisplayNameFor(model => model.Location)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.Location)
    </dd>

    </dl>
 </div>
 <p>
@Html.ActionLink("Edit", "Edit", new { id = Model.ID }) |
@Html.ActionLink("Back to List", "Index")
</p>'

在上面的粗体区域,我收到错误

  

对象引用未设置为对象的实例。

请告诉我之所以收到此错误的原因以及解决方法是什么。

2 个答案:

答案 0 :(得分:0)

SingleOrDefault将返回&#34;默认&#34; (如果找不到与给定条件匹配的对象,则对于引用类型(如类实例)null。您描述错误的最可能原因是Persons的对象实例为空。

答案 1 :(得分:0)

如注释中所指定的,此错误是因为Persons objecte变为null,使用null-coalescing operator {??)执行此类null检查

   public ActionResult Index(int id)
    {
        PersonContext PC = new PersonContext();
        Persons PS = PC.persons.SingleOrDefault(pr => pr.ID == id);
        PS = PS ?? new Persons();
        return View(PS);
    }