Useful Serialization Methods of LINQ to SQL objects

I am just going through a project for my senior “Projects in Information Systems” class, commenting most of the complex logic. I came across these two methods I wrote to serialze LINQ to SQL objects. They came in pretty handy, so I thought I’d share even though they don’t have error-handling. I’m not too embarrassed.

The way I used them was pretty ghetto, I was having troubles getting the objects I needed to serialize to be used in a Session object (I thnk it had something to do with an Order_Details table having two foreign keys to the same table, Ledger, for an IN and OUT field). Anyway, I serialed the object to XML and just stored the whole string into a listBox’s value. I know that’s begging for poor performance, and overriding the data validation checks is opening the ASP.NET page up for security issues, but the only people who are going to use this are me and my instructor. So, it was a quick work around. I could have stored it in a Session Object as a string, but then I would have had to call some funky work around for the listBox. Anyway, enough about that.

/// <summary>
/// Serializes a LINQ object to an XML string
/// </summary>
/// <typeparam name="T">Type of the Object</typeparam>
/// <param name="linqObject">The LINQ object to convert</param>
/// <returns>string</returns>
public static string SerializeLINQtoXML<T>(T linqObject)
{
   // see http://msdn.microsoft.com/en-us/library/bb546184.aspx
   DataContractSerializer dcs = new DataContractSerializer(linqObject.GetType());

   StringBuilder sb = new StringBuilder();
   XmlWriter writer = XmlWriter.Create(sb);
   dcs.WriteObject(writer, linqObject);
   writer.Close();

   return sb.ToString();
}

/// <summary>
/// Deserializes an XML string to a LINQ object
/// </summary>
/// <typeparam name="T">The type of the LINQ Object</typeparam>
/// <param name="input">XML input</param>
/// <returns>Type of the LINQ Object</returns>
public static T DeserializeLINQfromXML<T>(string input)
{
   DataContractSerializer dcs = new DataContractSerializer(typeof(T));

   TextReader treader = new StringReader(input);
   XmlReader reader = XmlReader.Create(treader);
   T linqObject = (T)dcs.ReadObject(reader, true);
   reader.Close();

   return linqObject;
}

Related Articles