Store .NET objects inside an Azure Table Storage and then retrieve them back in their original type

Non-relational databases are becoming more and more popular as a solution for storing your data. Cloud solutions like Microsoft Azure also get more popular with every day.

Currently Azure supports two types of “NoSQL” databases in the Azure portal. The one is DocumentDB (the NoSQL option in the main menu of the portal) and the other is the Table Storage (from the Storage accounts option in main menu). Do not confuse this Table with the tables of a relational database, they are not the same! A detailed analysis of the differences and similarities of the two technologies is beyond the purpose of this article, but we can summarize them to the following points:

  • DocumentDB can store complex structures of data like a list of objects or a list of lists with objects. On the other hand a Table Storage allows only key-value pairs of simple types (strings, numbers, booleans).

  • The DocumentDB-API supports more operations and query types with the database than a Table Storage. For querying a Table we have to make use of the Partition or Row Key.

  • Hosting a DocumentDB costs more money than hosting a Table Storage.

  • As one should expect from a NoSQL database, both options are very fast and are the optimal solution for use as data stores for huge amounts of information.

In order to be able to store complex object structures inside a Table Storage, we have to serialize these objects into a string. Does this process reminds you of something? Yes, JSON. Then we can deserialie the results of a query and we have again the complex objects in our C# code.

In the code that follows you see a working example. We first connect to the database, we add a new entity inside a Table and we then query this entity back into the C# environment. I have added several comments for each step of the process to make the code more understandable.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using Newtonsoft.Json;

namespace StoreComplexObjectsInTable
{
	class Program
	{
		static void Main(string[] args)
		{
			// Make a connection to the Table Storage account
			CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
				"YOUR-ACCOUNT-NAME-AND-ACCOUNT-KEY-STRING");

			// Create a Table client
			CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

			// Get a reference to the table we want to add new entities in
			CloudTable table = tableClient.GetTableReference("THE-NAME-OF-THE-TABLE");

			// create this table if it does not already exist
			table.CreateIfNotExists();

			// Start by creating a new Person object. 
			// Scroll down to find more information about the properties of the class
			List<string> hobbies = new List<string>() { "swimming", "programming" };

			var child1 = new Child()
			{
				Firstname = "John",
				Age = 10
			};

			var child2 = new Child()
			{
				Firstname = "Mary",
				Age = 15
			};

			List<Child> childs = new List<Child>() { child1, child2 };

			// Serialize the complex types into strings and store them in the Person TableEntity
			var person = new Person("Christos")
			{
				Lastname = "Monogios",
				Hobbies = JsonConvert.SerializeObject(hobbies),
				Children = JsonConvert.SerializeObject(childs)
			};

			// Add the entity to the table
			TableOperation operation = TableOperation.InsertOrMerge(person);
			table.Execute(operation);

			// Create a new query to retrieve the inserted entity back
			TableQuery<Person> query = new TableQuery<Person>();

			// execute the query against the Table Storage
			var result = table.ExecuteQuery<Person>(query);

			// We got the answer. Now we have to deserialize the strings into complex objects
			// Notice that we use the generic method in order to define the type
			//  we want to convert the string to.
			var firstPerson = result.First();
			var firstPersonHobbies = JsonConvert.DeserializeObject<List<string>>(firstPerson.Hobbies);
			var firstPersonChildrens = JsonConvert.DeserializeObject<List<Child>>(firstPerson.Children);

			// Show the deserialized properties
			foreach (var hobby in firstPersonHobbies)
			{
				Console.WriteLine(hobby);
			}

			foreach (var child in firstPersonChildrens)
			{
				Console.WriteLine(child.Firstname);
			}

			Console.ReadLine();
		}
	}
}

And here are the POCO classes. Remember that the class/ classes which we store in a Table Storage have to inherit from the TableEntity class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// remember to inherit your POCOs from the TableEntity class
class Person : TableEntity
{
    public Person()
    {
    }

    public Person(string firstname)
    {
        this.PartitionKey = firstname;
        this.RowKey = DateTime.UtcNow.Ticks.ToString();
    }

    public string Lastname
    {
        get; set;
    }

    public string Hobbies
    {
        get; set;
    }

    public string Children
    {
        get; set;
    }
}

class Child
{
    public string Firstname
    {
        get; set;
    }

    public int Age
    {
        get; set;
    }
}

Are you interested in the cloud technologies and especially in Azure? Drop me a line if you have any remark or question. I would be glad to help you.

comments powered by Disqus