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.

image

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].

Let-s create some sample entities:

public class Food
   {
       [Key]
       // Primary Key, when the PK is the name of the class + id the annotation is not needed
       public int FoodId { getset; }
 
       public string Name { getset; }
       public DateTime ExpireDate { getset; }
       public bool StillInFridge { getset; }
 
       // Define a relationship Many to Many between Food and Recipe, an intermediate table will be created 
       public virtual List<Recipe> UsedForRecipes { getset; }
   }
 
   public class Recipe
   {
       // Primary Key
       public int RecipeId { getset; }
 
       // EF needs the virtual attribute to enable Lazy loading 
       public virtual List<Food> Ingredients { getset; }
 
   }

Continue reading