How to: Connect to Azure SQL Database Using the ADO.NET Entity Framework
Updated: November 26, 2014
The ADO.NET Entity Framework enables developers to create data access applications by programming against a conceptual application model instead of programming directly against a relational storage schema.
This topic shows how to create a simple conceptual model, that is mapped to a Microsoft and have the sample School database created on your server. To create the sample School database, see Getting Started with Microsoft Azure SQL Database and complete steps one through eight.
Create the data model
In Visual Studio, on the File menu, point to New, and then click Project.
In the New Project dialog box, in the Installed templates list, select either Visual Basic or Visual C#, and then EF Designer from database, and then click Next.
Click New Connection, then in the Choose Data Source dialog box select Microsoft SQL Server, and then click Continue.
In the Connection Properties dialog box, enter the fully qualified name of the sever in the Server name box. For example, z8ue9o20al.database.windows.net.
In the Log on to the server box, select Use SQL Server Authentication and enter the credentials for the database administrator. For example, tester or tester@ z8ue9o20al.database.windows.net.
Click the Test Connection button to validate the logon information.
In the Connect to a database box, select Select or enter a database name and then select the School database from the list. Click OK.
In the Entity Data Model Wizard, choose No, exclude sensitive data from the connection string. I will set it in my application code option. Then, click Next.
Select the most recent version of the Entity Framework, and then click Next..
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SchoolApplicationEF { class Program { private static SchoolEntities schoolContext; static void Main(string[] args) { //Initialize the ObjectContext using (schoolContext = new SchoolEntities()) { // Define a query that returns all People // objects ordered by last name. var personQuery = from p in schoolContext.People.Include("Courses") orderby p.LastName select p; Console.WriteLine("List of people: "); try { foreach (Person per in personQuery) Console.WriteLine("{0} {1}", per.FirstName, per.LastName); } catch (Exception ex) { Console.WriteLine("An error occurred: " + ex.Message); } } Console.WriteLine("Hit enter..."); Console.Read(); } } }
Migrate the application to SQL Database
In the SchoolEFApplication project, open the App.Config file. Change the connection string so that it connects to your Azure Azure SQL Database. The console window will show the names of all the people in the School database.
See Also