Serialize C# class directly to SQL server?

.net, c#, serialization, sql-server

Solution

You can xml serialize the class into an xml field. We use this all the time for exception logging in an ETL.

Using the XmlSerializer you may want a helper method somewhere which serializes the class to a string...

public static string SerializeToXml<T>(T value)
{
    StringWriter writer = new StringWriter(CultureInfo.InvariantCulture);
    XmlSerializer serializer = new XmlSerializer(typeof(T));
    serializer.Serialize(writer, value);
    return writer.ToString();
}

Then just put the string into the db like any other.

Problem

can anyone suggest the best way to serialize data (a class actually) to a DB? I am using SQL server 2008 but i presume i need to serialize the class to a string / or other data type before storing in the database? I presume that this field needs to be text or binary?? Does SQL server 2008 (or .net 3.5) support serializing directly tothe database ?? Any help really appreciated

Original source