Question

I'm having some problems with retrieving my Project entity in the EntityFramework. It keeps giving me the Objest instance has been disposed error.

I've got 2 instances, as seen in the image below.enter image description here

And the following code gives me the error:

    public Project GetProjectyById(int id)
    {
        using (var context = new CoderaDBEntities())
        {
            return context.Projects.First(c => c.Id == id);
        }
    }

Everything from Project is retrieved fine, but the Category object inside the Project object (the association) delivers me the object has been disposed error. What's going on?

Thanks!

Edit: Does this association look odd to you?

Was it helpful?

Solution

It looks like you are attempting to access the Category related object using Lazy Loading when the DBContext object has already been disposed (wrapping it in a using statement will dispose it once it goes out of scope). Lazy Loading is when EF loads related entities only when they are requested in the code.

To avoid this you should explicitly load the related object with a Include statement :

return context.Projects.Include("Category").First(c => c.Id == id);

alternatively you could load this in a strongly typed fashion as below but be sure to add the 'using System.Data.Entity; ' reference

return context.Projects.Include(x => x.Category).First(c => c.Id == id);

Another alternative is to allow for Lazy Loading by not wrapping the DbContext object in a using statement as below.

  public Project GetProjectyById(int id)
    {
        var context = new CoderaDBEntities() 
        return context.Projects.First(c => c.Id == id);       
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top