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

http://www.microsoft.com/en-us/download/details.aspx?id=8363

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
[yourname].tt
Which will contain simple POCO classes for each entity in your model
[yourname].tt
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”>
<Columns>
<asp:BoundField DataField=”Category” HeaderText=”Category” />
<asp:BoundField DataField=”CreatedByUserName” HeaderText=”User” />
<asp:BoundField DataField=”DateTime” HeaderText=”DateTime” />
</Columns>
</asp:GridView>

In the code behind:

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

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