Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert System.Data.Entity.DynamicProxies to (non proxy) class in C#

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

like image 212
brian4342 Avatar asked Sep 24 '15 12:09

brian4342


1 Answers

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(); 
}
like image 91
brian4342 Avatar answered Oct 20 '22 03:10

brian4342