skip to Main Content

Im doing a MVC app but when I try to run it, it shows the following errors

System.ObjectDisposedException: ‘The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.’
item.Plan.Plan_Days = ‘item.Plan.Plan_Days’ threw an exception of type ‘System.NullReferenceException’

@model IEnumerable<POS.Models.Faculty>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Crear Nuevo", "Guardar")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Organization_Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.First_Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Last_Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Job_Title)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Email)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Photo)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Address)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Phone_Number)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Meal_Plan_Status)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Plan.Plan_Days)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Organization_Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.First_Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Last_Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Job_Title)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Email)
        </td>
        <td>
            <img src=" @Html.DisplayFor(modelItem => item.Photo)" width="200" />
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Address)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Phone_Number)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Meal_Plan_Status)
        </td>
        <<td>
            @Html.DisplayFor(modelItem => item.Plan.Plan_Days)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Employee_ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.Employee_ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Employee_ID })
        </td>
    </tr>
}

</table>

This is the controller:

using POS.Datos;
using POS.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace POS.Controllers
{
    public class FacultyController : Controller
    {
        FacultyAdmin admin = new FacultyAdmin();

        // GET: Faculty
        public ActionResult Index()
        {
            return View(admin.Consultar());
        }

        public ActionResult Guardar()
        {
            ViewBag.mensaje = "";
            return View(); 
        }

        public ActionResult Nuevo(Faculty modelo)
        {
            admin.Guardar(modelo);
            ViewBag.mensaje = "Informacion Guardada";
            return View("Guardar",modelo);
        }
    }
}

Code of FacultyAdmin.cs:

using POS.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace POS.Datos
{
    public class FacultyAdmin
    {
        public void Guardar(Faculty modelo)
        {
           using (Cafeteria_POSEntities context = new Cafeteria_POSEntities())
            {
                context.Faculties.Add(modelo);
                context.SaveChanges();  
            }
        }

        public IEnumerable<Faculty>Consultar()
        {
            using (Cafeteria_POSEntities context = new Cafeteria_POSEntities())
            {
                return context.Faculties.AsNoTracking().ToList(); //AsNoTracking para no hacer copia en  memoria porque no se hace ningun CRUD 
            }
        }
    }
}

Faculties definition:

// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
    
using System;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;

namespace POS.Models
{
    
    public partial class Cafeteria_POSEntities : DbContext
    {
        public Cafeteria_POSEntities()
            : base("name=Cafeteria_POSEntities")
        {
        }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }
    
        public virtual DbSet<Faculty> Faculties { get; set; }
        public virtual DbSet<KU_Students> KU_Students { get; set; }
        public virtual DbSet<Language_Students> Language_Students { get; set; }
        public virtual DbSet<Menu> Menus { get; set; }
        public virtual DbSet<Order> Orders { get; set; }
        public virtual DbSet<Plan> Plans { get; set; }
        public virtual DbSet<Station> Stations { get; set; }
        public virtual DbSet<sysdiagram> sysdiagrams { get; set; }
    }
}

2

Answers


  1. Use .Include() to load related entities before using the data in the view:

    public IEnumerable<Faculty>Consultar()
    {
        using (Cafeteria_POSEntities context = new Cafeteria_POSEntities())
        {
          return context.Faculties.Include(p => p.Plan).AsNoTracking().ToList(); 
        }
    }
    

    The problem here is your Entity Framework context by default configured to use the Lazy Loading. Means related data still not loaded when you tried to use in the Index view.

    Therefore when the Index view is trying to query the data the context is actually does not exist.

    Login or Signup to reply.
  2. You need to Eager Loading for Plan data that is related to Faculty.

    FacultyAdmin.cs

    public IEnumerable<Faculty>Consultar()
    {
        using (Cafeteria_POSEntities context = new Cafeteria_POSEntities())
        {
            return context.Faculties
                .Include(x => x.Plan)  // Eager Load related Plan data
                .AsNoTracking()
                .ToList();
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search