0

(警告新手)我正在使用 codefirst 实体框架(使用 MVC3)并尝试显示步骤列表及其相关问题。不知道为什么我的语法会引发异常“ObjectContext 实例已被释放,不能再用于需要连接的操作。”:

@model IEnumerable<COPSGMIS.Models.Step>

@{
    ViewBag.Title = "Questionaire";
}

<h2>Questionaire</h2>
   @using (Html.BeginForm("Questionaire", "Question", FormMethod.Post, new { id = "SignupForm" }))
   {
       <div>
            @foreach (var item in Model)
            {
              <fieldset class="wizard">
                <legend class="wizard">@Html.DisplayFor(modelItem => item.Title)</legend>
                @foreach (var question in item.Questions)
                //*** item.Questions is throwing an exception  ****
                {
                <label for="question">@Html.DisplayFor(modelItem => question.QuestionText)</label>
                <input id="question" type="text" /> 
                }
              </fieldset>
            }            
        <p>
            <input id="SaveAccount" type="button" value="Save" />
        </p>
    </div>
   }

我的模型:

public int StepID { get; set; }
        public int ReviewID { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public int StepOrder { get; set; }
        public virtual ICollection<Question> Questions { get; set; }

我的控制器:

var steps = from b in db.Steps
                            orderby b.StepOrder
                            select b;
                return View(steps.ToList());
4

1 回答 1

0

当 item.Questions 被访问时,EF 将尝试访问数据库以获取该项目的问题。如果上下文已被释放,它将失败。由于您将遍历视图中的问题,因此建议您使用“包含”将它们添加到您的初始查询中。

var steps = from b in db.Steps.Include(s => s.Questions)
            orderby b.StepOrder
            select b;

return View(steps.ToList());
于 2012-11-29T16:53:12.067 回答