Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

Code First Entity Framework - .NET Framework

RSS
Modified on Fri, May 19, 2017, 12:12 PM by Administrator Categorized as Entity Framework Code First, ┬ĚNet Framework

Overview

This article walks through getting started with a Code First Entity Framework solution.

Walkthrough

STEP 1: Install EntityFramework package

  • Visual Studio > Tools menu > Library Package Manager > Package Manager Console
  • In the Package Manager Console window: Install-Package EntityFramework.

STEP 2: Create DbContext-based class

A DbContext-based class is a class that inherits from System.Data.Entity.DbContext.

using System.Data.Entity;

namespace NerdDinner.Domain
{
    public class SiteDb : DbContext
    {
        public DbSet<Dinner> Dinners { get; set; }
        public DbSet<RSVP> RSVPs { get; set; }
    }
}

STEP 3: Create connection string

In web.config, create a connection string NAMED THE SAME as the DbContext-based class

<connectionStrings>
  <add name="SiteDb"
       connectionString="Data Source=.;Initial Catalog=NerdDinners;Integrated Security=SSPI;" 
       providerName="System.Data.SqlClient"
       />
</connectionStrings>

STEP 4: Setup Database Sync

To have the database be recreated when the model changes, add one of the following two blocks to Application_Start() in Global.asax.cs.

if (System.Diagnostics.Debugger.IsAttached)
    Database.SetInitializer<SiteDb>(new DropCreateDatabaseIfModelChanges<SiteDb>());

if (System.Diagnostics.Debugger.IsAttached)
    Database.SetInitializer<SiteDb>(new SiteDbInitializer());

Alternatively, you could set this up in the web.config file, like this.

<configuration>
  . . .
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <contexts>
      <context type="CompanyName.ProjectName.Data.MyDomain, CompanyName.ProjectName.Data">
        <databaseInitializer type="System.Data.Entity.MigrateDatabaseToLatestVersion`2[[CompanyName.ProjectName.Data.MyDomain, CompanyName.ProjectName.Data], [CompanyName.ProjectName.Data.Migrations.Configuration, CompanyName.ProjectName.Data]], EntityFramework" />
      </context>
    </contexts>
  </entityFramework>
  . . .
</configuration>

The SiteDbInitializer class might have code like the following.

using System.Data.Entity;
. . .
public class SiteDbInitializer : DropCreateDatabaseIfModelChanges<SiteDb>
{
    protected override void Seed(SiteDb context)
    {
        var dinners = new List<Dinner>
        {
            new Dinner
            {
                Title = "Sample Dinner 1",
                EventDate = new DateTime(2012,12,31),
                Address = "One Microsoft Way",
                Country = "USA",
                HostedBy = "scottgu@microsoft.com"
            },
            new Dinner
            {
                Title = "Sample Dinner 2",
                EventDate = new DateTime(2013,5,31),
                Address = "Somewhere Else",
                Country = "USA",
                HostedBy = "scottgu@microsoft.com"
            }
        };
        dinners.ForEach(d => context.Dinners.Add(d));
    }
}

Conventions

To remove the pluralizing of table names, include the following code within your DbContext-based class.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
    modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}

Package Manager Commands

  • Use the update-database -script command to generate a SQL script, including the INSERT statement against the [__MigrationHistory] table, for the current migrations.

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2018, Patrick Jasinski.