Asp.net延迟加载相关实体

时间:2017-03-02 06:16:13

标签: c# asp.net .net asp.net-mvc entity-framework

我使用的是Asp.net vs 2012,我的课程是

public class klasa
{
    [Key]
    public int klasaid { get; set; }
    public string emriklases { get; set; }
    public string vendodhja { get; set; }
    public virtual ICollection<student> students { get; set; }
}
public class student
{
    [Key]
    public int studentid { get; set; }
    public string emristudent { get; set; }
    public int nota { get; set; }
    public int klasaid { get; set; }
    [ForeignKey("klasaid")]
    public klasa Klasa { get; set; }

学生列表控制器

udb _db = new udb();
public ActionResult Index([Bind(Prefix="klsasaid")] int klasaid)
{
    var studentlist = _db.Seuni.Find(klasaid);
    if (studentlist != null)
    {
        return View();
    }
    return HttpNotFound();
}

学生列表查看索引

@model Unilast.Models.klasa
<h2>List for @Model.emriklases </h2>
@Html.Partial("_partial1", @Model.students);
<p>@Html.ActionLink("Create New", "Create")</p>

_partial1查看如下:

@model IEnumerable<Unilast.Models.student>

<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.emristudent)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.nota)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.klasaid)

延迟加载实体不起作用。

  

参数字典包含'Unilast.Controllers.StudentListController'中方法'System.Web.Mvc.ActionResult Index(Int32)'的非可空类型'System.Int32'的参数'klasaid'的空条目。可选参数必须是引用类型,可空类型,或者声明为可选参数。   参数名称:参数

这是它失败的错误 视图是

2 个答案:

答案 0 :(得分:1)

像这样修改你的控制器

    public ActionResult Index(int? id)
    {

        if (! id.HasValue || id.Value < 1 )
        {
            return HttpNotFound();
        }

        List<String> studentList = new List<string>();
        var klasa = _db.Keuni.FirstOrDefault(x => x.klasaid == id.Value);
        if (studentList != null)
        {
           return View(klasa);
        }
        else
        {
            return HttpNotFound();
        }
    }

答案 1 :(得分:0)

在您的学生班中, [ForeignKey(“klasaid”)] 需要放在声明之上。你把它放在下面。