运行linq查询时出错

时间:2015-11-04 04:44:53

标签: c# linq

我收到此错误

"{"There is already an open DataReader associated with this Command which must be closed first."}" 

以下是它出错的代码。

var summaryViewModel = new YogaSpaceSummaryViewModel
            {
                SpaceImage = (from u in space.Images orderby u.Ordering ascending select u.ImageThumbnail).First(),
                Title = space.Overview.Title,
                SpaceId = space.YogaSpaceId,
                DateCreated = space.DateCreated.ToShortDateString(),
                StepsToList = space.StepsToList,
                Status = space.Status
            };

此代码的哪一部分

YogaSpaceOverviewViewModel overviewViewModel = new YogaSpaceOverviewViewModel();

        foreach (YogaSpace space in yogaSpaces)
        {
            var summaryViewModel = new YogaSpaceSummaryViewModel
            {
                SpaceImage = (from u in space.Images orderby u.Ordering ascending select u.ImageThumbnail).First(),
                Title = space.Overview.Title,
                SpaceId = space.YogaSpaceId,
                DateCreated = space.DateCreated.ToShortDateString(),
                StepsToList = space.StepsToList,
                Status = space.Status
            };

            overviewViewModel.YogaSpaceSummarys.Add(summaryViewModel);
        }

3 个答案:

答案 0 :(得分:1)

您可能希望使用using向下包装,因此范围将导致所有对象被置于隐藏状态。此外,为了避免使用已放置的datacontext的lzy加载问题,您最好将ToList() ot FirstOrDefault()更好地提供给您返回的任何结果,以确保已枚举该集合,并且如果上下文是处置然后一切都很花哨。

答案 1 :(得分:0)

 <connectionStrings>
 <add name="DatabaseEntities" connectionString="metadata=res://*/Database.csdl|res://*/Database.ssdl|res://*/Database.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=Server;Initial Catalog=Database;Persist Security Info=True;User ID=sa;Password=passowrd;MultipleActiveResultSets=True;Application Name=EntityFramework&quot;" providerName="System.Data.EntityClient" />
 </connectionStrings>

在Webconfig中启用 MultipleActiveResultSets

答案 2 :(得分:0)

将MultipleActiveResultSets = true添加到连接字符串的提供程序部分(指定数据源,初始目录等)。