将List 保存到ASP.NET中的会话

CartItems保存在SQL数据库中。

我想将所有CartItem放入List并转移到Instance.Items。

实例变量将保存到会话中。

代码如下。

public class ShoppingCart { public List Items { get; private set; } public static SqlConnection conn = new SqlConnection(connStr.connString); public static readonly ShoppingCart Instance; static ShoppingCart() { if (HttpContext.Current.Session["ASPNETShoppingCart"] == null) { Instance = new ShoppingCart(); Instance.Items = new List(); HttpContext.Current.Session["ASPNETShoppingCart"] = Instance; } else { Instance = (ShoppingCart)HttpContext.Current.Session["ASPNETShoppingCart"]; } } 

返回List的代码。 我想将从此函数返回的List保存到Instance.Items。 这样它就可以保存到会话中。

  public static List loadCart(String CustomerId) { String sql = "Select * from Cart where CustomerId='" + CustomerId + "'"; SqlCommand cmd = new SqlCommand(sql, conn); List lstCart = new List(); try { conn.Open(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { CartItem itm = new CartItem(Convert.ToInt32(reader["ProductId"].ToString())); itm.Quantity = Convert.ToInt32(reader["Quantity"].ToString()); lstCart.Add(itm); } } catch (Exception ex) { } finally { conn.Close(); } return lstCart; } 

如果要将整个对象提交到会话,则应将项目存储在与对象的会话中。

为什么不做这样的事呢?:

 public class ShoppingCart { public List Items { get; private set; } public static SqlConnection conn = new SqlConnection(connStr.connString); public static readonly ShoppingCart Instance; static ShoppingCart RetrieveShoppingCart() { if (HttpContext.Current.Session["ASPNETShoppingCart"] == null) { Instance = new ShoppingCart(); Instance.Items = new List(); HttpContext.Current.Session["ASPNETShoppingCart"] = Instance; } else { Instance = (ShoppingCart)HttpContext.Current.Session["ASPNETShoppingCart"]; } return Instance; } }