如何序列化LINQ裡的實體Table(DBML產生出來的)
我們的Web AP有將Linq產生出來的Table Class放到Session中,因為要使用Session Mode使用StateServer所以要序列化才能放進Session中。
剛好找到如何序列化Linq里的實体列表(比如:DBML生成的),只是我改成放到Session之中,這樣就可以使用StateServer了!
using System.Text;
using System.Xml;
using System.Collections.Generic;
using System.IO;
public class Serializator
{
public static string SerializeLinqList<T>(List<T> list)
{
DataContractSerializer dcs = new DataContractSerializer(typeof(List<T>));
StringBuilder sb = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(sb))
{
dcs.WriteObject(writer, list);
}
return sb.ToString();
}
public static List<T> DeserializeLinqList<T>(string xml)
{
List<T> list;
DataContractSerializer dcs = new DataContractSerializer(typeof(List<T>));
using (XmlReader reader = XmlReader.Create(new StringReader(xml)))
{
list = dcs.ReadObject(reader) as List<T>;
}
if (list == null) list = new List<T>();
return list;
}
}
//使用它
const string SessionKey = "MySessionKey";
private List<Widget> WidgetList
{
get
{
List<Widget> widgets;
if (Session[SessionKey] == null)
{
widgets = new DashboardFacade().GetWidgetList();
Session[SessionKey] = Serializator.SerializeLinqList<Widget>(widgets);
}
else
{
string xml = (string)Session[SessionKey];
widgets = Serializator.DeserializeLinqList<Widget>(xml);
}
return widgets;
}
}
請注意,要用到.net 3.5 sp1哦!
Hi,
亂馬客Blog已移到了 「亂馬客 : Re:從零開始的軟體開發生活」
請大家繼續支持 ^_^