Persist a DataContract as XML in a database

Robert picture Robert · Jul 3, 2009 · Viewed 8.6k times · Source

I'm working on a kind of "store and forward" application for WCF services. I want to save the message in a database as a raw XML blob, as XElement. I'm having a bit of trouble converting the datacontract into the XElement type I need for the database call. Any ideas?

Answer

jasonmw picture jasonmw · Jul 3, 2009

this returns it as a string, which you can put into the db into an xml column. Here is a good generic method you can use to serialize datacontracts.

public static string Serialize<T>(T obj)
{
    StringBuilder sb = new StringBuilder();
    DataContractSerializer ser = new DataContractSerializer(typeof(T));
    ser.WriteObject(XmlWriter.Create(sb), obj);
    return sb.ToString();
}

btw, are you using linq to sql? The reason i ask is because of the XElement part of your question. if thats the case, you can modify this in the .dbml designer to use a string as the CLR type, and not the default XElement.