I'm working on a .Net 6 API that uses a Service Layer to do all the business logic of the Controllers. And I'm trying to use EF 6 on this layer using the "using" statement to be able to use de dbContext in a Singleton class. The problem is that once all the logic has been done and the Controller is mapping the object I get a "disposed object" error.
The Service Method
public async Task<StudiesResponse> GetAllStudies()
{
StudiesResponse studies = new StudiesResponse();
List<StudyReponse> list = new List<StudyReponse>();
StudyReponse resp;
try
{
using (var scope = _serviceProvider.CreateScope())
{
var _dbContext = scope.ServiceProvider.GetRequiredService<DataContext>();
foreach (Study study in _dbContext.Studies)
{
resp = new StudyReponse()
{
StudyCode = study.IXRSStudyCode,
Participators = _dbContext.RoleUsers.Where(x => x.Study.StudyId == study.StudyId).Select(x => new ParticipatorsResponse()
{
UserEmail = x.User.UserEmail,
RoleName = x.Role.Name
})
};
list.Add(resp);
}
}
studies.Studies = list;
}
catch (Exception e)
{ throw e; }
return studies;
}
My problem is that in the line "list.Add(resp);" my list of Participators is still with all the data. But once the code leaves the Using, the property Participators of the list variable is empty... I understand that the problem is that I'm getting it from the LinQ result from the _dbContext and it gets disposed. BUT I don't know why... I mean, I'm assigning it to a variable, why it's not sticking?
CodePudding user response:
Try adding ToList()
after .Select(x => new ParticipatorsResponse() { })
to persist the Participators
collection.
This is because the data is "lazy" and is only retrieved when iterating the the collection.
Since you iterate it outside the using block (probably where you call GetAllStudies()
), the connection is not valid anymore. The ToList()
iterates it and stores a list instead of a IEnumerable/IQueryable
.
resp = new StudyReponse()
{
StudyCode = study.IXRSStudyCode,
Participators = _dbContext.RoleUsers.Where(x => x.Study.StudyId == study.StudyId).Select(x => new ParticipatorsResponse()
{
UserEmail = x.User.UserEmail,
RoleName = x.Role.Name
}).ToList()
};