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].
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 { get; set; } public string Name { get; set; } public DateTime ExpireDate { get; set; } public bool StillInFridge { get; set; } // Define a relationship Many to Many between Food and Recipe, an intermediate table will be created public virtual List<Recipe> UsedForRecipes { get; set; } } public class Recipe { // Primary Key public int RecipeId { get; set; } // EF needs the virtual attribute to enable Lazy loading public virtual List<Food> Ingredients { get; set; } }