Windows Azure - SQL Azure - Using ADO.NET Entity Framework - Data Operations


The data model creation which is an essential part required was discussed in the previous article "Windows Azure - SQL Azure - Using ADO.NET Entity Framework - Creating DataModel".

Pre-Requisites

For working on this application, you need to have the following pre-requisites.

  • Azure project with web role
  • Entity data model with Employee class

You may use the project from the previous article.

After having the above, place the following on the Default.aspx page

  • 4 buttons with labels Insert, Update, Delete, Refresh
  • A grid control
SQL Azure Data Operations

Insert Operation

For creating a new employee, use the following code in the Insert button click event.

mysqlazureEntities context = new mysqlazureEntities();
 
Employee employe = new Employee();
employe.Name =
"New Employee from EF";
 
context.AddToEmployees(employe);
context.SaveChanges();

Update Operation

For creating a new employee, use the following code in the Update button click event.

mysqlazureEntities context = new mysqlazureEntities();
Employee employee = context.Employees.Where(emp => emp.Name == "New Employee from EF").FirstOrDefault();
 
if (employee != null)
    employee.Name =
"Updated Name"
context.SaveChanges();

Delete Operation

For creating a new employee, use the following code in the Delete button click event.

mysqlazureEntities context = new mysqlazureEntities();
Employee employee = context.Employees.Where(emp => (emp.Name == "New Employee from EF" || emp.Name=="Updated Name")).FirstOrDefault();
 
if (employee != null)
    context.DeleteObject(employee); 
context.SaveChanges();

Select Operation

For creating a new employee, use the following code in the Refresh button click event.

GridView grid = GridView1; 

grid.Columns.Clear();
grid.Columns.Add(
new BoundField() { HeaderText = "Id", DataField = "Id" });
grid.Columns.Add(
new BoundField() { HeaderText = "Name", DataField = "Name" });
 
mysqlazureEntities context = new mysqlazureEntities();
grid.DataSource = context.Employees.ToList();
grid.DataBind();


On executing the application and playing with the buttons you can view the following results.

windows Azure Data Operations

Summary

In this article we have explored the data operations using ADO.NET Entity Framework over our SQL Azure database. You need to change the database name, user name and password in the configuration file.

Up Next
    Ebook Download
    View all
    Learn
    View all