Reputation: 75133
I'm having some troubles using Session Variables as they are being used as Reference and I want to use them as value.
I got to this debuging my solution and I created something like:
DataTable dt =
(DataTable)HttpContext.Current.Session[
"SearchReturn-DataTableSchema"];
// Adding Rows of Data to DataTable dt
HttpContext.Current.Session["SearchReturn-DataTable"] = dt;
((DataTable)HttpContext.Current.Session[
"SearchReturn-DataTableSchema"]).Rows.Clear();
return dt;
my idea was to have in "DataTableSchema" only the DataTable with the Columns Schema and in "DataTable" the Columns + Rows.
Problem is that when I clear all rows from DataTableSchema, the variable dt will have the Rows cleared as well (!!)
How can avoid this? How can assign a variable (in this case a Session variable) as a value and not as a reference?
Thank you.
Answer
this
DataTable dt = (DataTable)Session["SearchReturn-DataTableSchema"];
needs to be this:
DataTable dt = ((DataTable)Session["SearchReturn-DataTableSchema"]).Copy();
:-)
Upvotes: 3
Views: 722
Reputation: 3239
Also You can Clone DataTable Schema using Clone method. And then Load data via Load and CreateReader methods.
Upvotes: 0
Reputation: 1064204
An interesting part of this is that the behaviour will depend on your session-state provider. You are presumably using the in-process provider at the moment, which keeps references - but most providers (understandably) use serialization.
This often bites people when they try to scale up, as they find that they have something non-serializable in session. So you might consider pushing state into a different provider; SQL-Server, memcached, etc - they will all do serialization so the data will be independent.
Upvotes: 2
Reputation:
Use the .Copy() Method of your DataTable:
http://msdn.microsoft.com/en-us/library/system.data.datatable.copy.aspx
Upvotes: 0