我试图在我的视图中使用以下代码填充部分视图:
@{Html.RenderAction("AppointmentsView", "Appointment", new { id = Model.PatientId });}
我的动作结果如下:
public ActionResult AppointmentsView(int id)
{
using (var context = new WaysToWellnessDB())
{
IEnumerable<AppointmentDiary> appointments = context.AppointmentDiaries.Where(a => a.PatientId == id).ToList();
var accountUsers = context.AccountUsers.Select(rr => new SelectListItem { Value = rr.AccountUserId.ToString(), Text = rr.FirstName + " " + rr.LastName }).ToList();
ViewBag.AccountUsers = accountUsers;
var location = context.Locations.Select(rr => new SelectListItem { Value = rr.LocationId.ToString(), Text = rr.LocationDesc }).ToList();
ViewBag.Location = location;
return PartialView("/Views/Patient/Appointment/_ViewAppointments.cshtml", appointments);
}
}
我的部分观点如下:
@foreach (var item in Model)
{
<tr>
<td>@Html.DisplayFor(x => item.DateTimeScheduled)</td>
<td>@Html.DisplayFor(x => item.AppointmentLength)</td>
<td>@Html.DisplayFor(x => item.AccountUser.FirstName) @Html.DisplayFor(x => item.AccountUser.LastName)</td>
<td>@Html.DisplayFor(x => item.Location.LocationDesc)</td>
<td>@Html.DropDownListFor(x => item.AttendedStatusId, (IEnumerable<SelectListItem>)ViewBag.AppointmentStatus, null, htmlAttributes: new { @class = "form-control", @id = "appointmentStatusId", onchange = "alert(this.options[this.selectedIndex].value);" })</td>
</tr>
}
这是falling down,说明如下:
ObjectContext实例已被处置,不能再用于需要连接的操作。
我尝试使用。include在我的linq查询,但这没有工作。有什么想法吗,为什么这不起作用?
Alexander Derck的回答是,我需要在顶部的using语句中包含System.Data.Entity,然后下面的工作
public ActionResult AppointmentsView(int id)
{
using (var context = new WaysToWellnessDB())
{
IEnumerable<AppointmentDiary> appointments = context.AppointmentDiaries.Include(p => p.AccountUser).Include(p => p.AttendedStatus).Include(p => p.Location).Where(a => a.PatientId == id).ToList();
return PartialView("/Views/Patient/Appointment/_ViewAppointments.cshtml", appointments);
}
}
您已经实现了"using"块,一旦执行"using"块,它就会处理对象。因此,当您试图访问虚拟属性"item.AccountUser。FirstName",因为上下文对象已经被处置,它抛出"ObjectContext实例已被处置"错误。正如Alexander Derck所发布的,使用include将解决这个问题,因为当上下文对象仍然存活时,您提前包含了所有必需的虚拟属性。