How to Persist (Store) Objects in a Database Using Serialization in .NET

Once in a while, you need to persists your objects, that is store them for later use, be it for use across multiple applications or a single application. .NET provides a serialization mechanism for achieving this. So, let’s start off with an example. Let’s say you have two applications and one of them instantiates objects of the same base class and stores them in a database, while the other one reads them from the database and executes a method on each object. As an example, let’s create a base class called Kiddo and two subclasses called Jimmy and Janice:

[Serializable]
public abstract class Kiddo
{

	public string Name { get; set; }

	public Kiddo(string name)
	{
		this.Name = name;
	}

	public void Hello()
	{
		Console.WriteLine(this.Name + " says Hello! " + this.KiddoSays());
	}

	public abstract string KiddosSay();

}

[Serializable]
public class Jimmy : Kiddo
{

	public Jimmy() : base("Jimmy")
	{
	}

	public override string KiddoSays()
	{
		return "Yo, I dig C#!";
	}

}

[Serializable]
public class Janice : Kiddo
{

	public Janice() : base("Janice")
	{
	}

	public override string KiddoSays()
	{
		return "I totally serialized!";
	}

}

Now notice that there is a [Serializable] class attribute that is on all of these classes – that will allow for serializing objects of these classes, i.e. allowing to store them in serialized form and instantiating them later on by deserializing them. Also note that I declared the Kiddo class as abstract so you can’t instantiate it. However, you can instantiate the Jimmy and Janice classes. Also notice that the KiddoSays method is overridden in both of the classes and says a different thing. If you were to simply use these classes, you will find them work just as expected, having the correct output. Now, what if you were to access them from a different application? – on to serialization.

Because we have [Serializable] attributes, we can now serialize our objects in a binary or XML format. I personally prefer XML because you can literally see all the properties with their values. One thing to note is that any property you want to persist has to be declared as a public property, with both getter and setter, and both public. You will also need a parameterless constructor so watch out for situations when a property has not been serialized or a property you may not have when deserializing in a project using an older version of your class – .NET will still create an object for you.

Now, the fun part. As I mentioned, I prefer XML serialization – it can be troubleshooted much easier. And now that we got our classes done, it’s a jiff. Let’s first create a table that will hold our objects:

CREATE TABLE MyKiddos
{
	KiddoId INT PRIMARY KEY IDENTITY(1, 1),
	[Type] NVARCHAR(50) NOT NULL,
	[Xml] NVARCHAR(MAX) NOT NULL
}

Now, we need the Type column so that we know which object we need to instantiate. It does not have to be the actual type name, it can simply be an identifier. You may want to use the actual type name, however, since then you can use reflection to pass in the actual type object to deserializer object, even if you still hard-code it. And finally, on to the C# code that will store our objects in the database:

public void StoreMe()
{
	var xs = new XmlSerializer(this.GetType());
	var sw = new StringWriter();
	xs.Serialize(sw, this);
	using (var db = new SqlConnection(connectionString))
	{
		db.Open();
		try
		{
			using (var cmd = new SqlCommand("INSERT INTO Mykiddos ([Type], [Xml]) VALUES (@Type, @Xml)", db))
			{
				cmd.Parameters.Add("@Type", this.GetType().Name);
				cmd.Parameters.Add("@Xml", sw.ToString();
				cmd.ExecuteNonQuery();
			}
		}
		finally { db.Close(); } 
	}
}

Now, towards the end of this, you may encounter a couple of errors along the way since I’ve been writing the code in notepad without validation. Those, if any, should be apparent to you. If you have questions, ask me and I’ll get back to you 🙂

Examine your new [Xml] column and you’ll see right away what’s happening. Suggestion: play around with using interfaces, abstracts, private and protected properties and such. You’ll also find out that there is more than storing values of an object, but that’s for some other time 🙂

See how to Deserialize an object that is stored as XML in the database.

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

One Response to How to Persist (Store) Objects in a Database Using Serialization in .NET

  1. Wonderful publish. I’m going through several these difficulties.

Leave a Reply

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