The ObjectContext instance has been disposed and can no longer be used

asp.net-mvc c# dispose entity-framework

Accepted Answer

You have a few choices to prevent this. Keep your navigation properties from being declared asvirtual or make your context's Slow loading behavior disabled. By making instances of derived proxy types and then overriding them, lazy loading is enabled by default.virtual add the loading hook properties. Therefore, I advise disabling lazy loading if you intend to work with a serializer:

public class YourContext : DbContext 
{ 
    public YourContext() 
    { 
        this.Configuration.LazyLoadingEnabled = false; 
    } 
}

These websites will assist you in better understanding what I have said in my response:

If you take away thevirtual EF won't generate a proxy class to lazy load your navigation properties since the POCO entity doesn't comply with the conditions specified in the second link. However, if you turned off lazy loading, even if your navigational propertiesvirtual and no entity will load them. Disabling lazy loading is a good idea if you're using a serializer. The majority of serializers operate by gaining access to each property on a type instance.

You could also use the JsonIgnore attribute on navigation properties that you don't want to be serialized as part of your entity as a third alternative, but as I just mentioned, disabling lazy loading is the best choice.

5
6/9/2015 11:49:36 PM

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