我试图在一个看起来像这样的方法中查询:
Public Shared Function listParticipationsByTeamCount(ByVal count As Integer, ByVal challenge As Challenge) As List(Of Participation)
Dim participationList As List(Of Participation)
If count <> Nothing And challenge IsNot Nothing Then
Using db As New DatabaseEntities()
participationList = db.Participations.Where(Function(x) x.TeamCount = count And x.Challenge.Id = challenge.Id).OrderByDescending(Function(x) x.TeamCount).ThenBy(Function(x) x.Team.Name).ToList()
End Using
End If
Return participationList
End Function
我有一个参与表,参与和团队表之间有多对一的关系,以及多对多之间的关系参与和 TeamMember 表。在我的标记页面上,当我像这样迭代列表时,我尝试这样的事情:
<% For Each participation As Participation In participationsList%>
<tr>
<td><a class="external-link" href="<%= participation.Team.Website %>"><%= participation.Team.Name%></a></td>
<td><%= participation.Percentage%>%</td>
<td>
<% For Each member As TeamMember In participation.TeamMembers%>
<%= member.Name%><br />
<% Next%>
</td>
</tr>
<% Next%>
我收到以下错误:
ObjectContext实例已被释放,不能再用于需要连接的操作。
现在我理解这是因为我把查询放在一个使用中,在End Using
之后我无法获取相关对象,在查看此内容时我尝试将查询的using语句更改为:
Using db As New DatabaseEntities()
participationList = db.Participations.Include("Team").Include("TeamMember").Where(Function(x) x.TeamCount = count And x.Team.Id = team.Id).OrderByDescending(Function(x) x.TeamCount).ThenBy(Function(x) x.Team.Name).ToList()
End Using
这不起作用。我也试过像这样加载实体引用:
Using db As New DatabaseEntities()
participationList = db.Participations.Where(Function(x) x.TeamCount = count And x.Team.Id = team.Id).OrderByDescending(Function(x) x.TeamCount).ThenBy(Function(x) x.Team.Name).ToList()
For each part as Participation in participationList
part.TeamReference.Load()
part.TeamMembers.Load()
Next
End Using
错误仍然存在。如何将所有这些相关对象加载到我的参与列表中,这样我仍然可以在我结束后使用???我知道EF4现在默认会进行延迟加载,但即使我明确加载相关对象,它仍然无法正常工作。
编辑:感谢所有答案,这是一个没有多元化TeamMembers包括的问题,因为它是一个集合。这打破了整个查询。所以答案是:
Using db As New DatabaseEntities()
participationList = db.Participations.Include("Team").Include("TeamMembers").Where(Function(x) x.TeamCount = count And x.Team.Id = team.Id).OrderByDescending(Function(x) x.TeamCount).ThenBy(Function(x) x.Team.Name).ToList()
End Using
答案 0 :(得分:3)
问题似乎是您正在设置查询但不执行它。
因此,在退出using语句之前,应该遍历数据并将其放在域对象中。
答案 1 :(得分:2)
在第三个代码块中,您包括TeamMember
。但是,根据我在第二个代码块中看到的内容,您的导航属性是多元化的,因此请尝试包含TeamMembers
。