Calling 'Read' when the data reader is closed is not a valid operation error using Entity Framework database first approach

asp.net-mvc-5 asp.net-web-api asp.net-web-api2 entity-framework-6

Question

I am creating a Web API that will fetch information from a table using Entity Framework database-first approach using stored procedures. ListAllTeams_Result is the complex type object created in Entity Framework. I am looping through the import function GetAllTeams() and populating the complex type. I am getting an error in my business layer when trying to access the data access layer

The error that I am getting is the following code

var team = _teamRepository.GetAllTeams();

The result of the query cannot be enumerated more than once.

Note: this error is in the inner stack and doesn't stop the application from executing

foreach (var t in team)

Calling 'Read' when the data reader is closed is not a valid operation.

Note : This stops execution

Business Layer

public IEnumerable<TeamDto> GetTeam()
{
   var team = _teamRepository.GetAllTeams();

   if (team != null)
   {
       foreach (var t in team.ToList())
       {
           yield return Mapper.Map<TeamDto>(t);
       }
   }

   yield break;
}

DataAccess layer:

public IEnumerable<ListAllTeams_Result> GetAllTeams()
{
    using (var mcrContext = new MCREntities())
    {
        return (from team in mcrContext.ListAllTeams("")
                select new ListAllTeams_Result
                        {
                            TeamID = team.TeamID,
                            TeamDescription = team.TeamDescription,
                            CountryCode = team.CountryCode,
                            CreatedBy = team.CreatedBy,
                            CreatedDate = team.CreatedDate,
                            ModifiedBy = team.ModifiedBy,
                            ModifiedDate = team.ModifiedDate
                        });
    }
}
1
0
8/5/2017 10:43:00 AM

Popular Answer

I have found what the problem is. I had to add ToList in the return

using (var mcrContext = new MCREntities())
        {
            return (from team in mcrContext.ListAllTeams("")

                select new ListAllTeams_Result
                {
                    TeamID = team.TeamID,
                    TeamName = team.TeamName,
                    TeamDescription = team.TeamDescription,
                    CountryCode = team.CountryCode,
                    CreatedBy = team.CreatedBy,
                    CreatedDate = team.CreatedDate,
                    ModifiedBy = team.ModifiedBy,
                    ModifiedDate = team.ModifiedDate

                }).ToList();
        }
1
3/13/2017 2:12:53 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow