How to Deserialize Objects That Are Stored in a Database as XML

You can serialize objects and store them in a database using the .NET framework. How do you get them back, then? – It is a rather straight-forward code. I’m going to utilize the same example classes I used in the previous post that talks about persisting objects in a database. One pitfall is that you do need to know which object you are instantiating so, we are going to have a switch statement here.

var kiddos = new List();
var sql = "SELECT [Type], [Xml] FROM MyKiddoes WITH(NOLOCK)";
using (var db = new SqlConnection(connectionString))
{
	db.Open();
	try
	{
		using (var cmd = new SqlCommand("SELECT [Type], [Xml] FROM MyKiddoes", db))
		{
			using (var drr = cmd.ExecuteReader())
			{
				XmlSerializer xs = null;
				switch ((string)drr["Type"])
				{
					case "MyNamespace.Jimmy":
						xs = new XmlSerializer(typeof(Jimmy));
						break;
					case "MyNamespace.Janice":
						xs = new XmlSerializer(typeof(Janice));
						break;
				}
				if (xs == null) { return; }
				var sr = new StringReader((string)drr["Xml"]);
				kiddos.Add((Kiddo)serializer.Deserialize(sr));
			}
		}
	}
	finally { db.Close(); }
}

Wasn’t that difficult, was it? Note how all your methods are still working and all the public properties are preserved.

This entry was posted in C# and tagged , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *