Posts Tagged ‘binary serialization’
Serialize Linq objects
If you are trying to serialize Linq objects then you will have to foolow these steps:
1. First, you have to mark your data context as serializable:
2. Then, in order to avoid errors like “circular reference was detected while serializing an object of type…”, you will have to set “Access” to “Internal” on your object’s relations (It is a compromise, but it needs to be done):
3. You can now use these methods:
public static string Serialize(object o) { XmlSerializer serizer = new XmlSerializer(o.GetType()); StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); serizer.Serialize(sw, o); sw.Close(); return sb.ToString(); } public static T Deserialize<T>(string xml) { XmlSerializer serizer = new XmlSerializer(typeof(T)); StringReader sr = new StringReader(xml); return (T)serizer.Deserialize(sr); }
like this (example):
AddressBookDataContext data = new AddressBookDataContext(); string xml = LINQHelper.Serialize(data.AB_Offices.ToList()); //.. List< AB_Offices>list = LINQHelper. Deserialize<List<AB_Offices>>(xml);
It works!