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; } }
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.
public class FoodContext : DbContext { public DbSet<Food> Foods { get; set; } public DbSet<Recipe> Recipes { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { // This method can be used if we need a column with a name different than the // property modelBuilder.Entity<Food>() .Property(recipe => recipe.StillInFridge) .HasColumnName("InFridge"); } }
Test it!
We have everything already! Let’s create an entry in our database… We just need to add an object to our DbContext and SaveChanges:
class Program { static void Main() { using (FoodContext context = new FoodContext()) { context.Foods.Add(new Food { ExpireDate = new DateTime(2014, 7, 30), Name = "Eggs" }); // Save changes to database context.SaveChanges(); } } }
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:
References
Pingback: Entity Framework 6 – Enable Migrations | Juan Carlos Sanchez's Blog