I having a problem in my website where I have 2 objects held in session, both object are structured differently and do not have any links to each other (not intentionally). Both objects however, have a collection of "Travellers". What I am trying to do is modify one collection by adding or removing "Travellers", when a finish button is clicked, the modified collection will then be saved to the other object.
The problem is that for some reason when I modify one collection in one object, the modifications are also made to the collection in the other object.
Here's a rough example:
Dim bookingContext As BookingContext = Session("BookingContext")
Dim personSearchContext As PersonSearchContext = Session("PersonSearchContext")
Dim personId As Integer = Request.Form("PersonID")
Dim mode As String = Request.Form("Mode")
Select Case mode
Case "Add"
For Each traveller As PersonProfile In personSearchContext.Travellers
If traveller.PersonID = personId Then
personSearchContext.SelectedTravellers.Add(traveller)
Exit For
End If
Next
context.Session("PersonSearchContext") = personSearchContext
Case "Remove"
For Each traveller As PersonProfile In personSearchContext.SelectedTravellers
If traveller.PersonID = personId T开发者_StackOverflowhen
travellerSearchContext.SelectedTravellers.Remove(traveller)
Exit For
End If
Next
context.Session("PersonSearchContext") = personSearchContext
Case "Save"
bookingContext.Travellers = personSearchContext.SelectedTravellers
context.Session("BookingContext") = bookingContext
End Select
The issue is the Travellers collection within the object "BookingContext" is being updated when I add and remove from the collection within "PersonSearchContext". It's as though there is some sort of link or pointer between them.
Any ideas?
Cheers.
The problem is this line in your Save code:
bookingContext.Travellers = personSearchContext.SelectedTravellers
What you're doing there is taking the reference to the SelectedTravellers collection in the personSearchContext object and assigning the reference to the Travellers collection in the bookingContext object. This assignment means that bookingContext.Travellers is no longer a separate collection from personSearchContext.SelectedTravellers. They're now both references to the same object in memory.
精彩评论