I discussed Three simple steps to create Azure table in my last post. Just after submitting the post, I got a comment from Neil Mackenzie that I can avoid creation of context class [Step 2] in last post. He helped me with the link for the best practice on MSDN
This post is to accommodate suggestion given by him and recommendation given on MSDN.
In this post we will see how to create Azure table using CloudTableClient.CreatTableIfNotExist method.
Add References
If you are creating table from a console application then you need to add below references to your project,
System.Data.Service.Client
And Microsoft.WindowsAzure.Serviceruntime.dll
Create Entity class
To represent entity class, we need to create a class inheriting from class TableServiceEntity. SchoolEntity class will be as below,
If you notice in above code snippet there is no
- Row Key
- Partition Key
- Calling base class constructor [ As I discussed here ]
Now when you make object of SchoolEntity class, in intellisense you will get RowKey,PartitionKey and TimeStamp to set as below,
Creating Account object
Pass connection string as of your storage account.
Creating Table Client
Creating Table
Creating Table Context
Creating Object to Insert
Adding Object to table
Putting all the code together,
using System; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.StorageClient; namespace ConsoleApplication7 { class Program { static void Main(string[] args) { CloudStorageAccount account = CloudStorageAccount.Parse("connectionString"); CloudTableClient tableClient = new CloudTableClient( account.TableEndpoint.ToString(), account.Credentials); string tableName = "School"; tableClient.CreateTableIfNotExist(tableName); TableServiceContext context = tableClient.GetDataServiceContext(); SchoolEntity entity = new SchoolEntity { Age = 9, Name = "DJ", PartitionKey = "S", RollNumber = null , RowKey = Guid.NewGuid().ToString() }; context.AddObject(tableName, entity); context.SaveChanges(); Console.WriteLine("Saved"); Console.ReadKey(true); } } public class SchoolEntity : TableServiceEntity { public string Name { get; set; } public int ? RollNumber { get; set; } public int Age { get; set; } } }
In this way you can create a table. I hope this post was useful. Thanks for reading
If you find my posts useful you may like to follow me on twitter http://twitter.com/debug_mode or may like Facebook page of my blog http://www.facebook.com/DebugMode.Net If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you
Leave a Reply