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; }
 
   }

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 { getset; }
    public DbSet<Recipe> Recipes { getset; }
 
    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.

image

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

image

References

Advertisements

One thought on “Entity Framework 6 – Code First

Your feedback is important...

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s