Data Services (aka Astoria) : CRUD (Select / Insert / Update / Delete )

Creating Astoria is very easy and many of you might have tried that out. What important for us is to work with that data. If you are developing Visual Studio Solution then things are quite obvious as mentioned below,

Either you will have Astoria or you will create that service. I am not going in details how you can create that. Assume that you have a service running anywhere.

You create your client apps (Windows / Web) and the reference an assembly “System.Data.Services.Client”.

After that you need to create “Service Reference” like WCF / Web Service from your visual studio project. Add the required namespace on top of your code behind file where you are writing your code.

C : Create / Inserting Data

static void Main(string[] args)

{

//Initialize the consumed Astoria Service

DataServiceContext ctx = new DataServiceContext(new Uri(@"http://localhost:1116/TestDataService.svc/"));

//This option is very important for Inserting

ctx.MergeOption = MergeOption.AppendOnly;

//Create a new object to insert

Emp emp = new Emp() { Name = "Astoria Employee" };

//Add to the collection

ctx.AddObject("Emp", emp);

//Commit the changes to Database

ctx.SaveChanges();

}

U : Updating Data

static void Main(string[] args)

{

//Initialize the consumed Astoria Service

TestDataEntities ctx = new TestDataEntities(new Uri(@"http://localhost:1116/TestDataService.svc/"));

//Create a new object to insert

Emp emp = (from e in ctx.Emp where e.Id == 81 select e).First();

//Change the Employee Name

emp.Name = DateTime.Now.ToString();

//Update the collection

ctx.UpdateObject(emp);

//Commit the changes to Database

ctx.SaveChanges();

}

D : Deleting Data

static void Main(string[] args)

{

//Initialize the consumed Astoria Service

TestDataEntities ctx = new TestDataEntities(new Uri(@"http://localhost:1116/TestDataService.svc/"));

//Create a new object to insert

Emp emp = (from e in ctx.Emp where e.Id == 80 select e).First();

//Delete the entity

ctx.DeleteObject(emp);

//Commit the changes to Database

ctx.SaveChanges();

}

R : Read / Querying Astoria Service

static void Main(string[] args)

{

//Initialize the consumed Astoria Service

TestDataEntities ctx = new TestDataEntities(new Uri(@"http://localhost:1116/TestDataService.svc/"));

//Create a new object to insert

IEnumerable<Emp> emps = from e in ctx.Emp select e;

foreach (Emp emp in emps)

{

Console.WriteLine("Employee Id : [{0,2}] Name : {1}", emp.Id, emp.Name );

}

}

Namoskar!!!