The ObjectContext instance has been disposed and can no longer be used for operations that require a connection. in Reference table

asp.net asp.net-mvc-4 c# entity-framework sql

Question

The two tables I use are Customers and Country ( Entity Framework with vs 2012 )

enter image description here

The model class, too

 using System;
 using System.Collections.Generic;

 public partial class Customer
 {
     public int Id { get; set; }
     public string FirstName { get; set; }
     public string LastName { get; set; }
     public string Address { get; set; }
     public string Email { get; set; }
     public string Phone { get; set; }
     public Nullable<int> CountrryId { get; set; }
     public string Note { get; set; }

     public virtual Country Country { get; set; }
 }

I'm attempting to create a select query to retrieve all customers with a country name. But I consistently see the error message below.

enter image description here

1
28
8/15/2018 10:47:44 AM

Accepted Answer

You're trying to enter a property owned by an association.Country after disposing of the data context. Entity Framework is set to lazy loading of association properties by default. In other words, when you try to access the association property for the first time, it makes another journey to the database. Entity Framework has to employ a data context in order to perform this journey to the database. In such situation, the attempt would be to utilize the data context produced byjQGridDemoEntities db = new jQGridDemoEntities() which, regrettably, your code has disposed of at this point. You have left the with block, hence the data context has been deleted.

To solve this issue, you have three options:

  • When the data context is active, you can access the association property. Move the code in your using block where you access the association property more specifically.

  • Load the association property eagerly as described in the first link I provided.

    customers = db.Customers.Include(c => c.Country).ToList()

  • While the data context is active, explicitly choose the database data that you want to return. And create the json object you return using that data.

    customers = db.Customers.Select(c => new
    {
        c.Id,
        c.FirstName,
        c.LastName,
        c.Address,
        c.Email,
        c.Phone,
        CountryName = c.Country.Name,
        c.Note
    };
    
39
10/15/2015 9:22:01 AM

Popular Answer

ZZZ_tmp


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow