Friday, 28 December 2018

Code First migrations and deployment with the Entity Framework

The Code First Migrations feature solves this problem by enabling Code First to update the database schema instead of dropping and re-creating the database. In this tutorial, you'll deploy the application, and to prepare for that you'll enable Migrations.
  1. Disable the initializer that you set up earlier by commenting out or deleting the contextselement that you added to the application Web.config file.
    XML
    <entityFramework>
      <!--<contexts>
        <context type="ContosoUniversity.DAL.SchoolContext, ContosoUniversity">
          <databaseInitializer type="ContosoUniversity.DAL.SchoolInitializer, ContosoUniversity" />
        </context>
      </contexts>-->
      <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
        <parameters>
          <parameter value="v11.0" />
        </parameters>
      </defaultConnectionFactory>
      <providers>
        <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
      </providers>
    </entityFramework>
    
  2. Also in the application Web.config file, change the name of the database in the connection string to ContosoUniversity2.
    XML
    <connectionStrings>
      <add name="SchoolContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=ContosoUniversity2;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
    </connectionStrings>
    
    This change sets up the project so that the first migration creates a new database. This isn't required but you'll see later why it's a good idea.
  3. From the Tools menu, select NuGet Package Manager > Package Manager Console.
  4. At the PM> prompt enter the following commands:
    text
    enable-migrations
    add-migration InitialCreate
    
    enable-migrations command
    The enable-migrations command creates a Migrations folder in the ContosoUniversity project, and it puts in that folder a Configuration.cs file that you can edit to configure Migrations.
    (If you missed the step above that directs you to change the database name, Migrations will find the existing database and automatically do the add-migration command. That's okay, it just means you won't run a test of the migrations code before you deploy the database. Later when you run the update-database command nothing will happen because the database already exists.)
    Migrations folder