Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reading data with EF 6 in a Singleton Class

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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()
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading