Database Reference
In-Depth Information
Figure 3-12. SQL Azure connection strings
This section uses the ADO.NET connection string to create an ADO.NET 4.0 Entity Framework
application. You also use Visual Studio 2010, which at the time of this writing is a release candidate and
available to everyone, and which should be available by the time this topic is in your hands.
Before you start building your application, you need a database with data in it. Based on what
you've learned in this chapter, create a new SQL Azure database named EFAzure. Next, open the SQL file
for this chapter called CreateContactTable.sql , and run that script against the EFAzure database. The
script creates a single table called Contact and inserts about a dozen contact records.
The examples in the following two sections illustrate connecting to a SQL Azure database and
querying the database for contact records. The first example uses the ADO.NET connection string shown
in Figure 3-12, and the second uses the ADO.NET 4.0 Entity Framework. You have many options to
connect to a SQL Azure database, and this chapter shows you simple examples; later chapters show
more detailed examples.
Connecting Using ADO.NET
In this first example, you build a simple Windows Forms application and use ADO.NET to query the
EFAzure SQL Azure database. Follow these steps:
1.
Open Visual Studio 2010, and create a new Windows Forms Application
project.
2.
Open Form1 in design mode, and place a button and a ListBox on the form.
Double-click the button to view its Click event, and enter the following code.
Copy the ADO.NET connection string for your database from the dialog shown
in Figure 3-12, and use it to replace the bolded section shown in the code:
using (SqlConnection conn = new
SqlConnection("Server=tcp:servername.database.windows.net;Database=EFAzure;User
ID=userid;Password=mypassword;Trusted_Connection=False;Encrypt=True;"))
{
3.
try
{
SqlCommand cmd = new SqlCommand(@"SELECT FirstName, LastName
FROM Contact
ORDER BY LastName", conn);
cmd.Connection.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
Search WWH ::




Custom Search