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.
Next add an ADO.NET Entity Data Model template.
Choose the option to generate the model from an existing database.
Choose an existing connection to the AdventureWorks SQL Server database, or create one if needed.
Select the items to be included in the model..
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.
Modify the default windows form to have a DataGridView and a button as shown below.
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:
Hope that helps.
Joe Kunk
Okemos, MI