简体   繁体   中英

'The ObjectContext instance has been disposed' in Razor's Html.Raw()

I am trying to convert my model into a JSON string, as I wish to use a Knockout binding in this particular view.

First of all, I try to convert the model into a JSON string, like so:

@{
    var serializerSettings = new Newtonsoft.Json.JsonSerializerSettings();
    serializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
    var jsonData = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializerObject(Model, serializerSettings));
}

In the last line (the actual conversion), the following error occurs:

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

My controller simply gets the object from the DB, just like this:

public ActionResult Partner(int id)
{
    using(var db = new DatabaseContext())
    {
        var partner = db.Partners
            .Include(x => x.OperatingCountries)
            .Include(x => x.Secrets)
            .FirstOrDefault(x => x.Id = id);

        return View(partner);
    }
}

I've done exactly the same in another view where this error doesn't occur. What's causing this, and how do I proceed?

Entity objects from Entity Framework should not be used for serialization. The same problem happens when you store these objects in the distributed cache.

If you still want to use Entity objects for serialization, disable lazy loading.

context.Configuration.LazyLoadingEnabled = false;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM