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

10,886

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(); 
}
Share:
10,886
brian4342
Author by

brian4342

Researcher in Machine Learning and Data Analytics.

Updated on June 19, 2022

Comments

  • brian4342
    brian4342 almost 2 years

    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