-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

リストを更新するコンストラクターを学校のクラスに追加すると、例外が取り除かれます。たとえば、次のようになります。

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 に答える
0

遅延/イーガーローディングについて読むことをお勧めします。セクションがモデルにロードされることはありません...

于 2013-03-01T08:53:30.290 に答える