Hello friends, I have the following question, I have a method that returns a simple select to my table database AspNetUsers
, but when I call it, it throws me the following error:
The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
This is my code, it's very simple:
public JsonResult JSONUsers()
{
using (DBEnt db = new DBEnt())
{
try
{
var user = db.AspNetUsers.ToList();
return Json(user, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
throw;
}
}
}
when I stop my running code by "breakpoint" and I see the user variable I can see that it has ALL the data of my table and when I give it "F5" to return the response, it effectively throws a json, then, I realize or I imagine that the response is sent before the "query" is performed, I realized that this only happens to me with the tables that the Entity Framework generates for my users, roles, etc. Could someone tell me how to avoid this?
Your problem occurs because some relationship properties have not finished loading when you want to serialize the list.
A solution to this problem is to disable the
LazyLoadingEnabled
, so that it doesn't load related entities automatically.By doing this, only objects of type will be
AspNetUsers
loaded, if you need to load another entity, you can useInclude
For example:
If you want to disable
LazyLoadingEnabled
it by default, it could be done from its constructorDbContext
, as Rafael mentions in his answer.The problem you have is in the relationships of the navigation properties of the EntityFramework user authentication tables.
When you serialize the returned results to Json , you enter an " infinite loop " due precisely to the navigation properties that I already told you about the tables.
In your case the table
AspNetUsers
tries to load the related entities (navigation properties) and these in turn load the table again,AspNetUsers
which reloads the related entities again (and so on).This behavior is called Lazy-Loading , and is enabled by default to True by EntityFramework.
Try disabling it in your Constructor
BdContext
like this:NUNCA
The entity that you use persistent as a response from a , is not returnedwebapi
, for that there are classesmodel
ordto
(Data Transfer Object)In the folder
Model
create the classand then you map it using linq in the response
This way you control what data you are going to send serialized as json in the response