smart developer’s blog

This is a C# resource library! Free how to’s and best practices…

Posts Tagged ‘binary serialization

Serialize Linq objects

leave a comment »

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:

serialization_mode

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):

step2_1        step2_2

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!

Written by smartdev

April 3, 2009 at 4:01 pm

Posted in .Net

Tagged with , ,