-2

“/”应用程序中的服务器错误。

你调用的对象是空的。

说明:执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

异常详细信息:System.NullReferenceException:对象引用未设置为对象的实例。

Source Error: 


Line 29:         <th></th>
Line 30:     </tr>
Line 31:     @foreach (var sections in Model.Sections)
Line 32:     {
Line 33:         <tr>

我的模型

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace TechFactorsLMSV2.Models
{

public class School
{
    public int ID { get; set; }
    public string SchoolName { get; set; }
    public ICollection<Section> Sections { get; set; }
}
public class Section
{
    public int ID { get; set; }
    public string SectionName { get; set; }
    public ICollection<Student> Students { get; set; }
}

public class Student
{
    public int ID { get; set; }
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string Address { get; set; }
    public DateTime DateEnrolled { get; set; }

}

public class LMSDBContext : DbContext
{
    public DbSet<School> Schools { get; set; }
    public DbSet<Section> Sections { get; set; }
    public DbSet<Student> Students { get; set; }
}
}

我的控制器

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TechFactorsLMSV2.Models;

namespace TechFactorsLMSV2.Controllers
{
public class SchoolsController : Controller
{
    private LMSDBContext db = new LMSDBContext();

    //
    // GET: /Schools/

    public ActionResult Index()
    {
        return View(db.Schools.ToList());
    }
public ActionResult Detail(int id)
    {
        var model = db.Schools.Single(d => d.ID == id);
        return View(model);
    }
 } 
} 

我的观点

 TechFactorsLMSV2.Models.School

@{
ViewBag.Title = "Detail";
}

<h2>@Model.SchoolName</h2>

@Html.ActionLink("Add Section", "Create", "Section", new { SchoolId = @Model.ID }, null      

}

<table>
  <tr>
    <th>Sections</th>
    <th></th>
  </tr>
  @foreach (var sections in Model.Sections)
{
    <tr>
        <td>@sections.SectionName</td>
        <td>


        </td>

    </tr>
 }


</table>
4

2 回答 2

0

我建议阅读有关延迟/急切加载的内容。您的部分根本不会加载到模型中......

于 2013-03-01T08:53:30.290 回答
0

例如,如果您向学校班级添加一个构造函数来更新列表,它将摆脱异常;

public class School
{
    public int ID { get; set; }
    public string SchoolName { get; set; }
    public ICollection<Section> Sections { get; set; }

    public School()
    {
        Sections = new List<Section>();
    }
}

但正如@Peter 所说,您需要考虑如何填充这些内容,并经历所有不适合 SO 的内容。

于 2013-03-01T09:04:28.420 回答