Entity Framework Database First Walkthrough

This walk-through will cover how set up entity framework with a database first approach:

1. Install Entity Framework 4.1


2. Begin a new Project

Create a new model:

Right click on project–> add new item
Select data from the menu
Select ADO.Net Entity Data Model
Enter a name
Click add

Follow the prompts and to map to an existing database (ex. use a connection string)

3. Use dbContext code generation

On the design surface of the edmx model:

Right click–> add code generation item
Select code from the menu
Select ADO.Net dbContext generator
Enter a name (helps if this is the same as your model name)
Click add

This will create two new items in your project
Which will contain simple POCO classes for each entity in your model
Which will generate a drived dbContext to use for getting and changing data

4. Manipulate data

As an example, map to a gridview:

<asp:GridView ID=”GridView1″ AutoGenerateColumns=”false” runat=”server”>
<asp:BoundField DataField=”Category” HeaderText=”Category” />
<asp:BoundField DataField=”CreatedByUserName” HeaderText=”User” />
<asp:BoundField DataField=”DateTime” HeaderText=”DateTime” />

In the code behind:

InsightEntities topic = new InsightEntities();
GridView1.DataSource = topic.Topics.ToList();

Here InsightEntites is the name of our contextClass.

This will something like produce the following:

Category User DateTime
test category test user 09/01/2013