smart developer’s blog

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

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:


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);
		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 , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: