IList stored in Session is updated when local copy of the IList is changed
I am building a large, multi-area MVC project. (MVC 2 Beta).
I have a session wrapper class, in its own project, MySession, that looks like this:
Public Class MySession
Private Shared _userlist As String = "UserList"
Public Shared Property UserList() As IList
Get
If HttpContext.Current.Session(_userlist) Is Nothing Then
Return Nothing
Else
Return CType(HttpContext.Current.Session(_userlist), IList)
End If
End Get
Set(ByVal value As IList)
HttpContext.Current.Session(_userlist) = value
End Set
End Property
End Class
In a child area project, I build and save a List to Session through my wrapper:
Dim favoritesList = (开发者_开发技巧From m In db.getFavorites(UserId) Select m).ToList
MySession.UserList = favoritesList
This works fine. I later retrieve the list from session into a local variable, userList:
Dim userList As IList(Of getFavoritesResult)
userList = MySession.UserList
I then ADD a new item to the LOCAL userList (and will ask the user if they want to save it):
userList.Add(New getFavoritesResult With {.Id = addApp.AppId, .DisplayText = addApp.DisplayText, ...})
Here is where the problem occurs. Immediately after the above .Add method, the local userList has the new item added, BUT the userList stored in Session ALSO contains the new item that was added to the local list.
I don't want the list updated in session unless the user wants to save the new list, and I explicitly save it.
Why does this occur, and how do I only add the item to the local list, not the one currently in session?
Thanks, this is driving me nuts!
What you are storing in the session is a reference to a list. That is what you update when you update the session variable. If you really want these to be unconnected you will have to create a copy of the list when you put it in the session or create a copy when you retrieve it. I don't know the VB syntax but something like (C#):
var newList = new List(oldList);
This is happening because both variables are referencing the same list.
So when adding via one variable, you are adding to the same list.
You need to copy the list stored in MySession
, operate on the copy and when ready to save set MySession.UserList
to the copy.
You can easily copy the list this way:
Dim copy As IList = new List(MySession.UserList)
精彩评论