Entity Framework 6 – Code First

This post describes briefly how to use Entity Framework 6.1.1 to create a database out of a Model defined in code. The goal is to have a summary with all the steps needed with the minimum overhead of information. I will use a Console Application.

Pre Requisites

Install Entity Framework from Nuget.

By default the created App.config will create the database locally.

Define Entities

Each entity will create a Table in the database. Entities are defined with a class that must contains a primary key. This primary key must be the class name + Id or a property with the annotation [Key].

DbContext

The context is the object that will allows to make queries to our objects. The context must extends the class DbContext and define a DbSet for each table of the database. The method OnModelCreating can be used to customize the database using the Fluent AP. E.g. to give a column a name different to the name defined in the Entity property.

To see this database within Visual Studio, open the SQL Server Object Explorer View and add a new local server with the name “(localdb)\v11.0”. This is the name of the database that EF will create by default.

If everything was ok now you should be able to see the create database using the SQL Server Object Explorer View: