7

I am getting some data from the database and storing this in a global variable as shown:

//Global Variable
public static List<stuff> Stuff;

using (var context = new StuffContext()) 
{ 
    stuff = new List<stuff>();
    stuff = (from r in context.Stuff
                select r).ToList(); 
}

The problem I am having is that the context closes and when I wish to access some of the data stored in the global variable, I cannot.

The data is of System.Data.Entity.DynamicProxies.Stuff instead of Application.Model.Stuff which means I then receive this error when I try to do something with the data:

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

My question is how can I, using the above code as an example, convert / cast to the type that I want so that I can use the data else where in my application?

Edit: Quick screen grab of the error: enter image description here

brian4342
  • 1,265
  • 8
  • 33
  • 69
  • 3
    What specific operation gives you that error? Are you trying to access some property that uses lazy loading? – sstan Sep 24 '15 at 12:09
  • 2
    possible duplicate of [How to solve the error The ObjectContext instance has been disposed and can no longer be used for operations that require a connection](http://stackoverflow.com/questions/18398356/how-to-solve-the-error-the-objectcontext-instance-has-been-disposed-and-can-no-l) – sstan Sep 24 '15 at 12:13

2 Answers2

1

The Solution was due to lazy loading after all.

I had to tell the query to grab everything so that when the context closes I still had access to the data. This is the change I had to make:

public static List<stuff> Stuff;

using (var context = new StuffContext()) 
{ 
    stuff = new List<stuff>();
    stuff = (from r in context.Stuff
            .Include(s => s.MoreStuff).Include(s => s.EvenMoreStuff)
            select r).ToList(); 
}
brian4342
  • 1,265
  • 8
  • 33
  • 69
0

Try to Disable ProxyCreationEnabled In Your Project BbContext constructor As Follow:

Configuration.ProxyCreationEnabled = false;
AliNajafZadeh
  • 1,216
  • 2
  • 13
  • 22