【问题标题】:Calling 'Read' when the data reader is closed is not a valid operation error using Entity Framework database first approach关闭数据读取器时调用“读取”不是使用实体框架数据库优先方法的有效操作错误
【发布时间】:2017-08-03 07:39:32
【问题描述】:

我正在创建一个 Web API,它将使用 Entity Framework 数据库优先方法使用存储过程从表中获取信息。 ListAllTeams_Result 是实体框架中创建的复杂类型对象。我正在循环导入函数GetAllTeams() 并填充复杂类型。尝试访问数据访问层时,我的业务层出现错误

我得到的错误是以下代码

var team = _teamRepository.GetAllTeams();

查询的结果不能多​​次枚举。

注意:此错误在内部堆栈中,不会阻止应用程序执行

foreach (var t in team)

在数据读取器关闭时调用“读取”不是有效操作。

注意:这会停止执行

业务层

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;
}

数据访问层:

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
                        });
    }
}

【问题讨论】:

  • 如果我注释掉 using 块它可以工作,但这并不意味着我有一个打开的连接。我该如何处理这个

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


【解决方案1】:

我找到了问题所在。我必须在返回中添加 ToList

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多