Q79. How to insert entities into the Azure table?

In the previous question we learnt how to create a table, and now we will insert entities to it. Entities in the Azure table storage are similar to rows in relational database management systems. To insert entities into the Table storage, First we need to define an entity class which is derived from TableEntity class.

Define an Entity class


A model class should be derived from TableEntity to be used in an application to work with the table. The model class represents an entity in an Azure table and it includes three public properties as required by Azure Table Storage. They are: PartitionKey, RowKey and Timestamp. We define the entity class for the table ‘items’ as shown below.

Each Item entity has the following information - Item name, Description and Stock-in-Hand. As you can see, the class Item inherits from TableEntity. Note that TableEntity exposes three fields: PartitionKey, RowKey and Timestamp. The PartitionKey and RowKey fields are required to store an entity in a Table. The Timestamp property is a read-only property.

Add the following class to your project:
public class Item: TableEntity
{
	public Item(string category, string code)   : base(category, code) {  }
	public Item() { }
	public string ItemName { get; set; }
	public string Description { get; set; }
	public string Stock-in-Hand { get; set; }
}


We can also hard code the PartitionKey and the RowKey in the constructor of the class as shown below.

Using Microsoft.WindowsAzure.Storage.Table

public class Item : TableEntity
{
	public Item() 
	{  
		PartitionKey=”RawMaterial”;
		RowKey=Guid.NewGuid().ToString();
	}
	public string ItemName { get; set; }
	public string Description { get; set; }
	public string Stock-in-Hand { get; set; }
}


Each entity has a partition key and a row key, and is required to store the entity. The first constructor in the above example code uses a 'category' as the partition key and the 'code' as the row key. The constructor passes the partitionkey and rowkey values to the base class 'TableEntity'. A second constructor is needed to deserialize the object when the object is being retrieved from the storage.

After defining an entity, we can create an Item entity and add it to the table.

Item entity = new Item("RawMaterial", "R001")
{
   ItemName = "Brick",
   Description = "6 * 3"
};
 
TableOperation insertOperation = TableOperation.Insert(entity);
table.Execute(insertOperation);
Console.WriteLine("Entity inserted!");


In the above code example, we have created an instance of Item object by specifying the Item category and code. Next, we will create a TableOperation object to insert the entity.