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 a context class [Step 2] in the last post. He helped me with the link for
the best practice on
MSDN
This post is to accommodate a suggestion given by him and recommendation given on
MSDN.
In this post we will see how to create an Azure table using
CloudTableClient.CreatTableIfNotExist method.
Add References
If you are creating a table from a console application then you need to add the below
references to your project,
System.Data.Service.Client
And Microsoft.WindowsAzure.Serviceruntime.dll
Create Entity class
To represent the entity class, we need to create a class inheriting from class
TableServiceEntity. SchoolEntity class will be as below,
If you notice in the 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 the connection string 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;
using
WPFTileGame;
namespace
ConsoleApplication7
{
class Program
{
static void
Main(string[] args)
{
CloudStorageAccount account =
CloudStorageAccount.Parse("connectionString");
CloudTableClienttableClient = new
CloudTableClient(account.TableEndpoint.ToString(),account.Credentials);
stringtableName =
"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
static object
tableName { get; set;
}
public
static string
stringtableName { get;
set; }
public
static
CloudTableClient CloudTableClienttableClient {
get; set; }}
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.