While working with Windows Azure it makes me feel as if I am working on ADO.NET Entity Framework and WCF Data Service. Everything is entity based and connection opens up through context.
Lets see how can we create an application to add Movies to our database.
Following are the using block entry
We need Movies entity
After that you need to choose the data source. In this case we are using development fabric. We can just change the values of the fabric to actual azure with 512 bit key and account name.
Now we need to initialize the RoleInstance to be able to read the config values
Hence after that initialize the CloudStorageAccount and CloudTableClient.
You may use the LINQ to read also with a combination of AsTableServiceQuery
That’s it!!!
The complete code
//Initializing Role of cloud project to be able to read the config CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetting) => { configSetting(RoleEnvironment.GetConfigurationSettingValue(configName)); }); //Reading the connection from Config CloudStorageAccount sAcc; sAcc = CloudStorageAccount.FromConfigurationSetting("DataConnection"); //Initializing the CloudTableClient CloudTableClient tableClient = new CloudTableClient(sAcc.TableEndpoint.AbsoluteUri, sAcc.Credentials); //Setting the table name string tableName = "Movies"; //Creating the table in storage tableClient.CreateTableIfNotExist(tableName); //Initializung Context TableServiceContext context = tableClient.GetDataServiceContext(); //Adding new entry context.AddObject(tableName, new Movies() { PartitionKey = "Action", RowKey = Guid.NewGuid().ToString(), Timestamp = DateTime.Now, Title = "Never Released..." }); //Saving with retries context.SaveChangesWithRetries(); //Reading the values using LINQ var q = (from m in context.CreateQuery<Movies>(tableName) where m.PartitionKey == "Action" select m).AsTableServiceQuery<Movies>(); dg.DataSource = q.ToList(); dg.DataBind();
Namoskar!!!
Internet Explorer comes with a great RSS integration and by using that we can download the recording of MIX11.
I have the channel9 MIX link http://channel9.msdn.com/Events/MIX/MIX11 and after I open it in IE you get to see the RSS
After that I choose the type of video I want to download and open Zune (installed locally).
Now you download as you want
When we either use the Fluent API or the attribute to put restrictions to our properties and while adding if we violet that, error would occur. Code First provides us set of classes to capture them
Code First Model
public class Department
{
[Key]
public int DeptId { get; set; }
public string DeptName { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
}
public class Employee
public int EmpId { get; set; }
[MaxLength(3)]
public string EmpName { get; set; }
public virtual Department Dept { get; set; }
public class EmpContext : DbContext
public DbSet<Department> Depts { get; set; }
public DbSet<Employee> Emps { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
modelBuilder.Entity<Department>().Property(p => p.DeptName).HasMaxLength(2);
My Application Code (need to refer the namespace “System.Data.Entity.Validation”)
Database.SetInitializer<EmpContext>(new DropCreateDatabaseIfModelChanges<EmpContext>());
using (var db = new EmpContext())
var d1 = new Department() { DeptName = "IT" };
var d2 = new Department() { DeptName = "Software" };
new List<Employee>
new Employee() { EmpName = "Wriju", Dept = d2 },
new Employee() { EmpName = "Writam", Dept = d2 },
new Employee() { EmpName = "Sumitra", Dept = d2 },
new Employee() { EmpName = "Debajyoti", Dept = d2 }
}.ForEach(e => db.Emps.Add(e));
try
db.SaveChanges();
catch (DbEntityValidationException e)
foreach (var k in e.EntityValidationErrors)
foreach (var e1 in k.ValidationErrors)
Console.WriteLine("{0} - {1}", e1.PropertyName, e1.ErrorMessage);
Captured Errors
EmpName - The field EmpName must be a string or array type with a maximum length of '3'. DeptName - The field DeptName must be a string or array type with a maximum length of '2'. EmpName - The field EmpName must be a string or array type with a maximum length of '3'. EmpName - The field EmpName must be a string or array type with a maximum length of '3'. EmpName - The field EmpName must be a string or array type with a maximum length of '3'.
While working for a Code First project u need to refer the assembly from already installed EF 4.1 update. Otherwise you can use NuGet to easily achieve it
After that you run the command Install-Package EntityFramework at the command window
April 20, 2011 at 11 AM Pacific Time.
Please register at https://training.partner.microsoft.com/learning/app/management/LMS_ActDetails.aspx?UserMode=0&ActivityId=731858
Learn what is new in ADO.NET Entity Framework Code First 4.1
ADO.NET Entity Framework comes with a new update to make things simpler while accessing data.
· Background - no edmx, no visual model
· Assemblies
· Create and Load Database
· Data Annotations
· DbContext, Database classes
· Database Initializer
· Fluent API
· Configurable connection string
ADO.NET Entity Framework’s Code First 4.1 allows us to execute SQL queries directly. You may need to get one column output or quickly update a table. One thing we need to be careful about running these raw queries is that you need to be double sure about the validity of these…
If you are viewing this article and new to ADO.NET Entity Framework Code First then please visit my blog at http://blogs.msdn.com/b/wriju/archive/2011/04/10/ado-net-entity-framework-code-first-development.aspx
Option 1 If I want to add values to my database,
//Adding data through query var q1 = db.Database.ExecuteSqlCommand("INSERT INTO Departments(DeptName) Values('Test')");
Option 2 Now want to read data store it already available entity. You need to call .ToList() to trigger the execution.
//Reading data through query var q2 = db.Depts.SqlQuery("SELECT * FROM Departments").ToList();
Option 3 Want to read data but do not have any entity.
var q3 = db.Database.SqlQuery<string>("SELECT DeptName FROM Departments").ToList();
EF Code First supports Lazy Loading as Model (edmx). You need to define the navigation properties to set the relationship to load the query.
So if we try to implement the below code
1: public class Department
2: {
3: [Key] //To make it Primary Key and Identity
4: public int DeptId { get; set; }
5: public string DeptName { get; set; }
6:
7: //Create Employee navigation property for Lazy Loading (1:many)
8: public virtual ICollection<Employee> Employees { get; set; }
9: }
10:
11: /// <summary>
12: /// Employee class
13: /// </summary>
14: public class Employee
15: {
16: [Key] //To make it Primary Key and Identity
17: public int EmpId { get; set; }
18: public string FirstName { get; set; }
19: public string LastName { get; set; }
20: public int DeptId { get; set; }
21:
22: //Create Department navigation property for Lazy Loading
23: public virtual Department Department { get; set; }
24: }
Hence the line 8 and 23 together with virtual would create the 1:many relationship.
After adding data if we try to write the below code it would Lazy Load the data
using (var db = new EmpDeptContext()) { var d = from dept in db.Depts select dept; foreach (var d1 in d) { Console.WriteLine("+++++++++++++"); Console.WriteLine(d1.DeptName); Console.WriteLine("+++++++++++++"); foreach (var e1 in d1.Employees) { Console.WriteLine(e1.FirstName + " " + e1.LastName); } Console.WriteLine("============================="); } }
And by adding .Include we will get similar Immediate Loading.
var d = from dept in db.Depts.Include("Employees") select dept;
I liked LINQ to SQL for its clean approach of defining only code to be able to access the database. ADO.NET Entity Framework comes with a much more richer experience of you being the fine grained control over the code. In this current version we have Model First and Database First approaches, now we have Code First.
You need to install the ADO.NET Entity Framework Code First API from Microsoft. I will let you Bing it. After that assume that you have two tables Department and Employee. One Department can have many employees.
You need the EntityFramework assembly to be part of your reference. You also need ComponentModel.DataAnnotations. Your department and employee class would look like,
using System.Data.Entity; using System.ComponentModel.DataAnnotations; /// <summary> /// Department class /// </summary> public class Department { [Key] //To make it Primary Key and Identity public int DeptId { get; set; } public string DeptName { get; set; } //Create Employee navigation property for Lazy Loading (1:many) public virtual ICollection<Employee> Employees { get; set; } } /// <summary> /// Employee class /// </summary> public class Employee { [Key] //To make it Primary Key and Identity public int EmpId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public int DeptId { get; set; } //Create Department navigation property for Lazy Loading public virtual Department Department { get; set; } }
{ [Key] //To make it Primary Key and Identity public int DeptId { get; set; } public string DeptName { get; set; } //Create Employee navigation property for Lazy Loading (1:many) public virtual ICollection<Employee> Employees { get; set; } } /// <summary> /// Employee class /// </summary> public class Employee { [Key] //To make it Primary Key and Identity public int EmpId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public int DeptId { get; set; } //Create Department navigation property for Lazy Loading public virtual Department Department { get; set; } }
After that you need the context class to create the connection
public class EmpDeptContext : DbContext { public DbSet<Employee> Emps { get; set; } public DbSet<Department> Depts { get; set; } }
After that you write your application to add Departments and Employees and this will automatically create a database first at you localhost\sqlexpress (if no option provided), then enter the data into it.
var deptSoftware = new Department() { DeptName = "Software" }; var deptIT = new Department() { DeptName = "IT" }; using(var db = new EmpDeptContext()) { new List<Employee> { new Employee(){FirstName = "Wriju", LastName = "Ghosh", Department = deptSoftware}, new Employee(){FirstName = "Saswati", LastName = "Sanyal", Department = deptSoftware}, new Employee(){FirstName = "Wrishika", LastName = "Ghosh", Department = deptSoftware}, new Employee(){FirstName = "Writam", LastName = "Ghosh", Department = deptIT}, new Employee(){FirstName = "Debajyoti", LastName = "Ghosh", Department = deptIT}, new Employee(){FirstName = "Sumitra", LastName = "Ghosh", Department = deptIT} }.ForEach(e => db.Emps.Add(e)); int records = db.SaveChanges(); Console.WriteLine("{0} record(s) saved", records); }
That’s it!!! Isn’t it clean? No Edmx no extra resources.
Is very easy and can’t think of anything simple. I did it with my favorite TestDB database
Open SQL Server Management Studio. Right click the database and select Generate Script
After that run the wizard as below
Select “Script entire database and all database objects”
Select “Save to new query window” and click advanced.
Choose the property value of “Script for the database engine type” to “SQL Azure Database”
And also choose
Choose the property “Types of data to Script” to “Schema and data”. This would bring data along with the schema.
Now hit next and finish.
Note: If you have any table which has no clustered index then you will not be able to import them to SQL Azure.
Now you need to create a database at your SQL Azure (through Portal) and run the script from your SQL Management Studio. Done
You could also use SSIS and BCP to do the same. But this one is the easiest to me.
Just published one Channel 9 video on TFS 2010 covering
Ø How to create Collection
Ø How to create Team Project
Ø How to setup the security
Ø How to create Workspace
Ø How to configure Source Control
Ø How to configure Team Build
http://channel9.msdn.com/posts/TFS2010FirstLook
Thanks everyone. It was pleasure talking to all of you in India TechEd 2011 on “Choosing Right Data Access Methodologies”. It was a jam packed session and a lot of people were standing or sitting on the stage. I loved talking. Huge!!!
I have been getting emails to share resources. Let me tell you one thing. The slide and the recording will be available on TechEd 2011 India website. So keep watching.
Here I will share the demo and the database script. I have uploaded them at http://bit.ly/g3OQpJ
Steps to follow,
1. In your local SQL Server create a database TestDB .
2 Run the script “01 TechEd2011_TestDB_Create and Insert.sql ” from share. This will create the tables and dummy value to it.
3. Open the “DataAccess_Final.zip” file and change the connection strings in all .config files. Please feel free to comment here or send me email at wriju_ghosh@hotmail.com for any quick assistance.
ADO.NET Team blog http://blogs.msdn.com/b/adonet/
WCF Data Services Team blog http://blogs.msdn.com/b/astoriateam/
A big thank to everyone for coming in after heavy lunch and before the India world cup match. Amazing dedication and willingness to learn. Time was limited so was not able to show a many exciting things there. Keep watching my blog and I will keep things posted.