From Nothing to Binding a Collection in 5 Minutes with Entity Framework

So I thought I would just do it, use the Entity Framework, I mean how bad can it be? Well, pretty easy to be honest. Granted I just bound a collection to a GridView, but it was super easy. So I wanted to share with you want I did.

First I recommend you install Visual Studio 2008 SP 1, which installs several updates to Visual Studio and the .NET Framework, including Entity Framework support.

Then just create a Web Site in Visual Studio. The next step is to setup your database, in my case I used the Beer House database that I have installed on my local server. You can use what every existing database you want.

Next you need to add an ADO.NET Entity Model to your application. This is done just like adding any other item to the site, I like to right click on the root of the site and go from there.

This will invoke the Entity Data Model Wizard. In this case I chose to use an existing database, you could start from scratch with an empty data model.

In the next step you define the ConnectionString to the database, which is just the same as it has been for a while.

The next step is where you define what you going to include in your Entity Model, in this case I just included the entire database to get the full effect!

Now just finish the wizard and the next thing you will see is a nice shiny new Entity Model displayed before your eyes. I took a full snapshot for you here, but you can zoom in too, see the second screen shot.

Now to the good stuff. I added a GridView to the default page of the web site, the only thing left was to bind the data to the grid. Simple enough, I just used Linq to Entities and the syntax of Linq that is quickly becoming familiar to me and it was pretty simple.

Public Sub BindData()

    Dim dc As New TheBeerHouseModel.TheBeerHouseEntities
    Dim lna = From c In dc.tbh_Articles _
        Select New With {c.Title, c.Approved, c.ViewCount, c.AddedDate}

    GridView1.DataSource = lna

End Sub

Viola, I have the news articles from the Beer House database displayed. It is as simple as that. In under 5 minutes, I went from no site, to implementing Entity Framework and displaying data.

I have a big announcement I will be making very soon that will involve the entity framework. Needless to say I will be making some more posts about Entity Framework this summer.

Share This Article With Your Friends!