Sunday, December 28, 2008

Practical Entity Framework - Creating your first data display


This blog post is the first in a series of posts to explore how to use the Entity Framework from a practical standpoint.  The focus will be less on the "about" of Entity Framework and more on the "how".

This series is oriented to those developers who are interested in adopting the Microsoft Entity Framework as their primary data access development methodology.

My examples will use the Microsoft AdventureWorks database in SQL Server 2005 and Visual Studio 2008 SP1.  To provide some variety in the blogosphere, I will use Windows Forms and Visual Basic .Net rather than ASP.Net and C#.

Create a standard Windows Project

Using Visual Studio 2008 SP1 or later, create a new Visual Basic Windows project.

EF001_CreateProject


Next add an ADO.NET Entity Data Model template.

EF002_Add_EDM_Designer


Choose the option to generate the model from an existing database.

EF002_Add_EDM_Designer_Wizard1_From_Database

Choose an existing connection to the AdventureWorks SQL Server database, or create one if needed.

EF002_Add_EDM_Designer_Wizard2_Specify_Connection

Select the items to be included in the model..

EF002_Add_EDM_Designer_Wizard3_Specify_Objects

Click Finish.  The template will do its magic and create the entity data model.  You will notice that there is now a Model Browser panel in Visual Studio.

EF002_Add_EDM_Designer_Wizard4_Result.

Modify the default windows form to have a DataGridView and a button as shown below.

EF003_Run with Blank Grid and button.

The code behind for the form to display the Product table is simply as follows:

Imports System.Data.Objects
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Button1.Click
Call DisplayDataInGrid()
End Sub

Private Sub DisplayDataInGrid()
' Create the ObjectContext.
Dim context As ObjectContext = _
New ObjectContext("name=AdventureWorksEntities")

'
Set the DefaultContainerName for the ObjectContext.
context.DefaultContainerName = "AdventureWorksEntities"

Dim query As ObjectQuery(Of Product) = _
New ObjectQuery(Of Product)("Product", context)

Me.DataGridView1.DataSource = query
End Sub
End Class


And the result is:



EF005_Run Image.



Hope that helps.



Joe Kunk

Okemos, MI


SQL Server DBA Best Practices

A recent issue of SQL Server Magazine had a poster entitled "Brad M. McGehee's SQL Server DBA Best Practices", included courtesy of redgate software. 

The poster is a wealth of great information on how to be successful with Microsoft SQL Server.  Thank you redgate!

In case you missed it, you can get your own free copy of the poster or find a copy of the text on Brad's blog

It is definitely worth your time to give it a careful read.

Hope that helps.

Joe Kunk
Okemos, MI