Variable is Not Available Using dbContexts?
I have the following code that throws an error on the call for getOccupants within Using dbPC. Is there a way to make this value accessible in Using dbPC? Or a better way to accomplish this? I tried nesting Using dbPC inside of Using dbContext, but that also throws errors.
Protected Sub btnPushSemester_Click(sender As Object, e As EventArgs) Handles btnPushSemester.Click
Dim dbPC As New Campus6Entities
Dim dbContext As New pbu_housingEntities
Using dbContext
Dim get_Year = From p In dbContext.Configs _
Where p.Description = "year" _
Select p
Dim get_Term = From p In dbContext.Configs _
Where p.Description = "term" _
Select p
Dim thisYear = get_Year.First.textValue
Dim thisTerm = get_Term.First.textValue
Dim getOccupants = From p In dbContext.Residents _
Where p.semester = thisTerm _
Where p.year = thisYear _
Select p
End Using
Using dbPC
For Each row In getOccupants
Dim student_info = row
Dim PCstudent = From r In dbPC.RESIDENCies _
开发者_如何学运维 Where student_info.people_code_id = r.PEOPLE_ID _
Where r.ACADEMIC_YEAR = thisYear _
Where r.ACADEMIC_TERM = thisTerm _
Select r
For Each row2 In PCstudent
Dim student_info2 = row2
student_info2.DORM_BUILDING = student_info.Building1.building_code
student_info2.DORM_ROOM = student_info.Room1.room1
student_info2.RESIDENT_COMMUTER = "R"
student_info2.DORM_CAMPUS = "O000000001"
dbPC.SaveChanges()
Next
Next
End Using
End Sub
Because of deferred execution, the query is not actually executed until you iterate over the collection, but by that time, you have already disposed the dbContext object. Try enclosing all the code in the Using blocks:
Using dbPC As New Campus6Entities
Using dbContext As New pbu_housingEntities
'rest of code here
End Using
End Using
Declare getOccupants
outside of the using block. You can assign it inside the block, but you have to declare it outside or it goes out of scope before you actually need to use it.
精彩评论