entity framework 4 - Dbcontext with using-clause in Asp.Net Json-Call -
i ran problem when switching local development server local iis server (asp.net mvc4) using following controller-method:
public jsonresult getjsondata(string context, string language) { using (keyvaluedbcontext db = new keyvaluedbcontext()) { var entries = u in db.keyvalues ((u.context == context) && (u.language == language)) select u; return json(entries, jsonrequestbehavior.allowget); } }
using local server, received data when calling method javascript without problem. method retrieves collection of key-value pairs database repository , sends them client). after switching iis got exception telling me dbcontext had been disposed of (although using clause ends after return-statement). (nb: visual studio not able find jsonserializer.cs reason, when error occurred). switching following version solved problem completely:
public jsonresult getjsondata(string context, string language) { keyvaluedbcontext db = new keyvaluedbcontext(); var entries = u in db.keyvalues ((u.context == context) && (u.language == language)) select u; return json(entries, jsonrequestbehavior.allowget); }
in both cases, using-block:
using system; using system.collections.generic; using system.data; using system.data.entity; using system.linq; using system.web; using system.web.mvc; using beepov4.models; // project-models
my question: acceptable way use dbcontext purpose of json-calls (and dropping using-clause) or there particular downside or hidden problem should aware of?
try reading entries
memory entries.tolist()
before passing them json()
:
using (keyvaluedbcontext db = new keyvaluedbcontext()) { var entries = u in db.keyvalues ((u.context == context) && (u.language == language)) select u; return json(entries.tolist(), jsonrequestbehavior.allowget); }