"
 
 
 
ASP.NET (snapshot 2017) Microsoft documentation and samples

Code First Migrations and Deployment with the Entity Framework in an ASP.NET MVC Application

by Tom Dykstra

Download Completed Project or Download PDF

The Contoso University sample web application demonstrates how to create ASP.NET MVC 5 applications using the Entity Framework 6 Code First and Visual Studio 2013. For information about the tutorial series, see the first tutorial in the series.

So far the application has been running locally in IIS Express on your development computer. To make a real application available for other people to use over the Internet, you have to deploy it to a web hosting provider. In this tutorial, you’ll deploy the Contoso University application to the cloud in Azure.

The tutorial contains the following sections:

We recommend that you use a continuous integration process with source control for deployment, but this tutorial does not cover those topics. For more information, see the (xref:)source control and (xref:)continuous integration chapters of the (xref:)Building Real-World Cloud Apps with Azure e-book.

Enable Code First Migrations

When you develop a new application, your data model changes frequently, and each time the model changes, it gets out of sync with the database. You have configured the Entity Framework to automatically drop and re-create the database each time you change the data model. When you add, remove, or change entity classes or change your DbContext class, the next time you run the application it automatically deletes your existing database, creates a new one that matches the model, and seeds it with test data.

This method of keeping the database in sync with the data model works well until you deploy the application to production. When the application is running in production, it is usually storing data that you want to keep, and you don’t want to lose everything each time you make a change such as adding a new column. 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 contexts element that you added to the application Web.config file.

    [!code-xmlMain]
       1:  <entityFramework>
       2:    <!--<contexts>
       3:      <context type="ContosoUniversity.DAL.SchoolContext, ContosoUniversity">
       4:        <databaseInitializer type="ContosoUniversity.DAL.SchoolInitializer, ContosoUniversity" />
       5:      </context>
       6:    </contexts>-->
       7:    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
       8:      <parameters>
       9:        <parameter value="v11.0" />
      10:      </parameters>
      11:    </defaultConnectionFactory>
      12:    <providers>
      13:      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
      14:    </providers>
      15:  </entityFramework>
  2. Also in the application Web.config file, change the name of the database in the connection string to ContosoUniversity2.

    [!code-xmlMain]

       1:  <connectionStrings>
       2:    <add name="SchoolContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=ContosoUniversity2;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
       3:  </connectionStrings>

    This change sets up the project so that the first migration will create a new database. This isn’t required but you’ll see later why it’s a good idea.
  3. From the Tools menu, click Library Package Manager and then Package Manager Console.

    Selecting_Package_Manager_Console
  4. At the PM> prompt enter the following commands:

    enable-migrations
    add-migration InitialCreate

    enable-migrations command
    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 OK, 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 will already exist.)

    Migrations folder
    Migrations folder

    Like the initializer class that you saw earlier, the Configuration class includes a Seed method.

    [!code-csharpMain]

       1:  internal sealed class Configuration : DbMigrationsConfiguration<ContosoUniversity.DAL.SchoolContext>
       2:  {
       3:      public Configuration()
       4:      {
       5:          AutomaticMigrationsEnabled = false;
       6:      }
       7:   
       8:      protected override void Seed(ContosoUniversity.DAL.SchoolContext context)
       9:      {
      10:          //  This method will be called after migrating to the latest version.
      11:   
      12:          //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
      13:          //  to avoid creating duplicate seed data. E.g.
      14:          //
      15:          //    context.People.AddOrUpdate(
      16:          //      p => p.FullName,
      17:          //      new Person { FullName = "Andrew Peters" },
      18:          //      new Person { FullName = "Brice Lambson" },
      19:          //      new Person { FullName = "Rowan Miller" }
      20:          //    );
      21:          //
      22:      }
      23:  }

    The purpose of the Seed method is to enable you to insert or update test data after Code First creates or updates the database. The method is called when the database is created and every time the database schema is updated after a data model change.

Set up the Seed Method

When you are dropping and re-creating the database for every data model change, you use the initializer class’s Seed method to insert test data, because after every model change the database is dropped and all the test data is lost. With Code First Migrations, test data is retained after database changes, so including test data in the Seed method is typically not necessary. In fact, you don’t want the Seed method to insert test data if you’ll be using Migrations to deploy the database to production, because the Seed method will run in production. In that case you want the Seed method to insert into the database only the data that you need in production. For example, you might want the database to include actual department names in the Department table when the application becomes available in production.

For this tutorial, you’ll be using Migrations for deployment, but your Seed method will insert test data anyway in order to make it easier to see how application functionality works without having to manually insert a lot of data.

  1. Replace the contents of the Configuration.cs file with the following code, which will load test data into the new database.

    [!code-csharpMain]

       1:  namespace ContosoUniversity.Migrations
       2:  {
       3:      using ContosoUniversity.Models;
       4:      using System;
       5:      using System.Collections.Generic;
       6:      using System.Data.Entity;
       7:      using System.Data.Entity.Migrations;
       8:      using System.Linq;
       9:   
      10:      internal sealed class Configuration : DbMigrationsConfiguration<ContosoUniversity.DAL.SchoolContext>
      11:      {
      12:          public Configuration()
      13:          {
      14:              AutomaticMigrationsEnabled = false;
      15:          }
      16:   
      17:          protected override void Seed(ContosoUniversity.DAL.SchoolContext context)
      18:          {
      19:              var students = new List<Student>
      20:              {
      21:                  new Student { FirstMidName = "Carson",   LastName = "Alexander", 
      22:                      EnrollmentDate = DateTime.Parse("2010-09-01") },
      23:                  new Student { FirstMidName = "Meredith", LastName = "Alonso",    
      24:                      EnrollmentDate = DateTime.Parse("2012-09-01") },
      25:                  new Student { FirstMidName = "Arturo",   LastName = "Anand",     
      26:                      EnrollmentDate = DateTime.Parse("2013-09-01") },
      27:                  new Student { FirstMidName = "Gytis",    LastName = "Barzdukas", 
      28:                      EnrollmentDate = DateTime.Parse("2012-09-01") },
      29:                  new Student { FirstMidName = "Yan",      LastName = "Li",        
      30:                      EnrollmentDate = DateTime.Parse("2012-09-01") },
      31:                  new Student { FirstMidName = "Peggy",    LastName = "Justice",   
      32:                      EnrollmentDate = DateTime.Parse("2011-09-01") },
      33:                  new Student { FirstMidName = "Laura",    LastName = "Norman",    
      34:                      EnrollmentDate = DateTime.Parse("2013-09-01") },
      35:                  new Student { FirstMidName = "Nino",     LastName = "Olivetto",  
      36:                      EnrollmentDate = DateTime.Parse("2005-08-11") }
      37:              };
      38:              students.ForEach(s => context.Students.AddOrUpdate(p => p.LastName, s));
      39:              context.SaveChanges();
      40:   
      41:              var courses = new List<Course>
      42:              {
      43:                  new Course {CourseID = 1050, Title = "Chemistry",      Credits = 3, },
      44:                  new Course {CourseID = 4022, Title = "Microeconomics", Credits = 3, },
      45:                  new Course {CourseID = 4041, Title = "Macroeconomics", Credits = 3, },
      46:                  new Course {CourseID = 1045, Title = "Calculus",       Credits = 4, },
      47:                  new Course {CourseID = 3141, Title = "Trigonometry",   Credits = 4, },
      48:                  new Course {CourseID = 2021, Title = "Composition",    Credits = 3, },
      49:                  new Course {CourseID = 2042, Title = "Literature",     Credits = 4, }
      50:              };
      51:              courses.ForEach(s => context.Courses.AddOrUpdate(p => p.Title, s));
      52:              context.SaveChanges();
      53:   
      54:              var enrollments = new List<Enrollment>
      55:              {
      56:                  new Enrollment { 
      57:                      StudentID = students.Single(s => s.LastName == "Alexander").ID, 
      58:                      CourseID = courses.Single(c => c.Title == "Chemistry" ).CourseID, 
      59:                      Grade = Grade.A 
      60:                  },
      61:                   new Enrollment { 
      62:                      StudentID = students.Single(s => s.LastName == "Alexander").ID,
      63:                      CourseID = courses.Single(c => c.Title == "Microeconomics" ).CourseID, 
      64:                      Grade = Grade.C 
      65:                   },                            
      66:                   new Enrollment { 
      67:                      StudentID = students.Single(s => s.LastName == "Alexander").ID,
      68:                      CourseID = courses.Single(c => c.Title == "Macroeconomics" ).CourseID, 
      69:                      Grade = Grade.B
      70:                   },
      71:                   new Enrollment { 
      72:                       StudentID = students.Single(s => s.LastName == "Alonso").ID,
      73:                      CourseID = courses.Single(c => c.Title == "Calculus" ).CourseID, 
      74:                      Grade = Grade.B 
      75:                   },
      76:                   new Enrollment { 
      77:                       StudentID = students.Single(s => s.LastName == "Alonso").ID,
      78:                      CourseID = courses.Single(c => c.Title == "Trigonometry" ).CourseID, 
      79:                      Grade = Grade.B 
      80:                   },
      81:                   new Enrollment {
      82:                      StudentID = students.Single(s => s.LastName == "Alonso").ID,
      83:                      CourseID = courses.Single(c => c.Title == "Composition" ).CourseID, 
      84:                      Grade = Grade.B 
      85:                   },
      86:                   new Enrollment { 
      87:                      StudentID = students.Single(s => s.LastName == "Anand").ID,
      88:                      CourseID = courses.Single(c => c.Title == "Chemistry" ).CourseID
      89:                   },
      90:                   new Enrollment { 
      91:                      StudentID = students.Single(s => s.LastName == "Anand").ID,
      92:                      CourseID = courses.Single(c => c.Title == "Microeconomics").CourseID,
      93:                      Grade = Grade.B         
      94:                   },
      95:                  new Enrollment { 
      96:                      StudentID = students.Single(s => s.LastName == "Barzdukas").ID,
      97:                      CourseID = courses.Single(c => c.Title == "Chemistry").CourseID,
      98:                      Grade = Grade.B         
      99:                   },
     100:                   new Enrollment { 
     101:                      StudentID = students.Single(s => s.LastName == "Li").ID,
     102:                      CourseID = courses.Single(c => c.Title == "Composition").CourseID,
     103:                      Grade = Grade.B         
     104:                   },
     105:                   new Enrollment { 
     106:                      StudentID = students.Single(s => s.LastName == "Justice").ID,
     107:                      CourseID = courses.Single(c => c.Title == "Literature").CourseID,
     108:                      Grade = Grade.B         
     109:                   }
     110:              };
     111:   
     112:              foreach (Enrollment e in enrollments)
     113:              {
     114:                  var enrollmentInDataBase = context.Enrollments.Where(
     115:                      s =>
     116:                           s.Student.ID == e.StudentID &&
     117:                           s.Course.CourseID == e.CourseID).SingleOrDefault();
     118:                  if (enrollmentInDataBase == null)
     119:                  {
     120:                      context.Enrollments.Add(e);
     121:                  }
     122:              }
     123:              context.SaveChanges();
     124:          }
     125:      }
     126:  }

    The Seed method takes the database context object as an input parameter, and the code in the method uses that object to add new entities to the database. For each entity type, the code creates a collection of new entities, adds them to the appropriate DbSet property, and then saves the changes to the database. It isn’t necessary to call the SaveChanges method after each group of entities, as is done here, but doing that helps you locate the source of a problem if an exception occurs while the code is writing to the database.

    Some of the statements that insert data use the AddOrUpdate method to perform an “upsert” operation. Because the Seed method runs every time you execute the update-database command, typically after each migration, you can’t just insert data, because the rows you are trying to add will already be there after the first migration that creates the database. The “upsert” operation prevents errors that would happen if you try to insert a row that already exists, but it overrides any changes to data that you may have made while testing the application. With test data in some tables you might not want that to happen: in some cases when you change data while testing you want your changes to remain after database updates. In that case you want to do a conditional insert operation: insert a row only if it doesn’t already exist. The Seed method uses both approaches.

    The first parameter passed to the AddOrUpdate method specifies the property to use to check if a row already exists. For the test student data that you are providing, the LastName property can be used for this purpose since each last name in the list is unique:

    [!code-csharpMain]

       1:  context.Students.AddOrUpdate(p => p.LastName, s)

    This code assumes that last names are unique. If you manually add a student with a duplicate last name, you’ll get the following exception the next time you perform a migration.

    Sequence contains more than one element

    For information about how to handle redundant data such as two students named “Alexander Carson”, see Seeding and Debugging Entity Framework (EF) DBs on Rick Anderson’s blog. For more information about the AddOrUpdate method, see Take care with EF 4.3 AddOrUpdate Method on Julie Lerman’s blog.

    The code that creates Enrollment entities assumes you have the ID value in the entities in the students collection, although you didn’t set that property in the code that creates the collection.

    [!code-csharpMain]

       1:  new Enrollment { 
       2:      StudentID = students.Single(s => s.LastName == "Alexander").ID, 
       3:      CourseID = courses.Single(c => c.Title == "Chemistry" ).CourseID, 
       4:      Grade = Grade.A 
       5:  },

    You can use the ID property here because the ID value is set when you call SaveChanges for the students collection. EF automatically gets the primary key value when it inserts an entity into the database, and it updates the ID property of the entity in memory.

    The code that adds each Enrollment entity to the Enrollments entity set doesn’t use the AddOrUpdate method. It checks if an entity already exists and inserts the entity if it doesn’t exist. This approach will preserve changes you make to an enrollment grade by using the application UI. The code loops through each member of the EnrollmentList and if the enrollment is not found in the database, it adds the enrollment to the database. The first time you update the database, the database will be empty, so it will add each enrollment.

    [!code-csharpMain]
       1:  foreach (Enrollment e in enrollments)
       2:  {
       3:      var enrollmentInDataBase = context.Enrollments.Where(
       4:          s => s.Student.ID == e.Student.ID &&
       5:               s.Course.CourseID == e.Course.CourseID).SingleOrDefault();
       6:      if (enrollmentInDataBase == null)
       7:      {
       8:          context.Enrollments.Add(e);
       9:      }
      10:  }
  2. Build the project.

Execute the First Migration

When you executed the add-migration command, Migrations generated the code that would create the database from scratch. This code is also in the Migrations folder, in the file named <timestamp>_InitialCreate.cs. The Up method of the InitialCreate class creates the database tables that correspond to the data model entity sets, and the Down method deletes them.

[!code-csharpMain]

   1:  public partial class InitialCreate : DbMigration
   2:  {
   3:      public override void Up()
   4:      {
   5:          CreateTable(
   6:              "dbo.Course",
   7:              c => new
   8:                  {
   9:                      CourseID = c.Int(nullable: false),
  10:                      Title = c.String(),
  11:                      Credits = c.Int(nullable: false),
  12:                  })
  13:              .PrimaryKey(t => t.CourseID);
  14:          
  15:          CreateTable(
  16:              "dbo.Enrollment",
  17:              c => new
  18:                  {
  19:                      EnrollmentID = c.Int(nullable: false, identity: true),
  20:                      CourseID = c.Int(nullable: false),
  21:                      StudentID = c.Int(nullable: false),
  22:                      Grade = c.Int(),
  23:                  })
  24:              .PrimaryKey(t => t.EnrollmentID)
  25:              .ForeignKey("dbo.Course", t => t.CourseID, cascadeDelete: true)
  26:              .ForeignKey("dbo.Student", t => t.StudentID, cascadeDelete: true)
  27:              .Index(t => t.CourseID)
  28:              .Index(t => t.StudentID);
  29:          
  30:          CreateTable(
  31:              "dbo.Student",
  32:              c => new
  33:                  {
  34:                      ID = c.Int(nullable: false, identity: true),
  35:                      LastName = c.String(),
  36:                      FirstMidName = c.String(),
  37:                      EnrollmentDate = c.DateTime(nullable: false),
  38:                  })
  39:              .PrimaryKey(t => t.ID);
  40:          
  41:      }
  42:      
  43:      public override void Down()
  44:      {
  45:          DropForeignKey("dbo.Enrollment", "StudentID", "dbo.Student");
  46:          DropForeignKey("dbo.Enrollment", "CourseID", "dbo.Course");
  47:          DropIndex("dbo.Enrollment", new[] { "StudentID" });
  48:          DropIndex("dbo.Enrollment", new[] { "CourseID" });
  49:          DropTable("dbo.Student");
  50:          DropTable("dbo.Enrollment");
  51:          DropTable("dbo.Course");
  52:      }
  53:  }

Migrations calls the Up method to implement the data model changes for a migration. When you enter a command to roll back the update, Migrations calls the Down method.

This is the initial migration that was created when you entered the add-migration InitialCreate command. The parameter (InitialCreate in the example) is used for the file name and can be whatever you want; you typically choose a word or phrase that summarizes what is being done in the migration. For example, you might name a later migration “AddDepartmentTable”.

If you created the initial migration when the database already exists, the database creation code is generated but it doesn’t have to run because the database already matches the data model. When you deploy the app to another environment where the database doesn’t exist yet, this code will run to create your database, so it’s a good idea to test it first. That’s why you changed the name of the database in the connection string earlier – so that migrations can create a new one from scratch.

  1. In the Package Manager Console window, enter the following command:

    update-database

    The update-database command runs the Up method to create the database and then it runs the Seed method to populate the database. The same process will run automatically in production after you deploy the application, as you’ll see in the following section.

Deploy to Azure

So far the application has been running locally in IIS Express on your development computer. To make it available for other people to use over the Internet, you have to deploy it to a web hosting provider. In this section of the tutorial you’ll deploy it to Azure. This section is optional; you can skip this and continue with the following tutorial, or you can adapt the instructions in this section for a different hosting provider of your choice.

Using Code First Migrations to Deploy the Database

To deploy the database you’ll use Code First Migrations. When you create the publish profile that you use to configure settings for deploying from Visual Studio, you’ll select a check box labeled Update Database. This setting causes the deployment process to automatically configure the application Web.config file on the destination server so that Code First uses the MigrateDatabaseToLatestVersion initializer class.

Visual Studio doesn’t do anything with the database during the deployment process while it is copying your project to the destination server. When you run the deployed application and it accesses the database for the first time after deployment, Code First checks if the database matches the data model. If there’s a mismatch, Code First automatically creates the database (if it doesn’t exist yet) or updates the database schema to the latest version (if a database exists but doesn’t match the model). If the application implements a Migrations Seed method, the method runs after the database is created or the schema is updated.

Your Migrations Seed method inserts test data. If you were deploying to a production environment, you would have to change the Seed method so that it only inserts data that you want to be inserted into your production database. For example, in your current data model you might want to have real courses but fictional students in the development database. You can write a Seed method to load both in development, and then comment out the fictional students before you deploy to production. Or you can write a Seed method to load only courses, and enter the fictional students in the test database manually by using the application’s UI.

Get an Azure account

You’ll need an Azure account. If you don’t already have one, but you do have a Visual Studio subscription, you can activate your subscription benefits. Otherwise, you can create a free trial account in just a couple of minutes. For details, see Azure Free Trial.

Create a web site and a SQL database in Azure

Your web app in Azure will run in a shared hosting environment, which means it runs on virtual machines (VMs) that are shared with other Azure clients. A shared hosting environment is a low-cost way to get started in the cloud. Later, if your web traffic increases, the application can scale to meet the need by running on dedicated VMs. To learn more about Pricing Options for Azure App Service, read the documentation on Azure Docs

You’ll deploy the database to Azure SQL Database. SQL Database is a cloud-based relational database service that is built on SQL Server technologies. Tools and applications that work with SQL Server also work with SQL Database.

  1. In the Azure Management Portal, click New in the left tab, click See all in new blade, and then click Web App & SQL in the Web Section and finally Create.

    New button in Management Portal
    New button in Management Portal

The New Web App & SQL - Create wizard opens.

  1. In the blade, enter a string in the App name box to use as the unique URL for your application. The complete URL will consist of what you enter here plus the default domain of Azure App Services (.azurewebsites.net). If the App name is already taken, the Wizard will notify you of this with a red The app name is not available message. If the App name is available, you will get a green checkmark.

    Create with Database link in Management Portal
    Create with Database link in Management Portal
  2. In the Subscription Dropdown, please choose the Azure Subscription in which you want the App Service to reside.

  3. In the Resource Group text box, choose a Resource Group or create a new one. This setting specifies which data center your web site will run in. For more information about Resource Groups, read the documentation on Azure Docs.
  4. Create a new App Service Plan by clicking the App Service section, Create New, and fill in App Service plan (can be same name as App Service), Location, and Pricing tier (there is a free option).

  5. Click the SQL Database, and choose Create New or select an existing database

  6. In the Name box, enter a name for your database.
  7. Click the Target Server box, select Create a new server. Alternatively, if you previously created a server, you can select that server from list of available servers.
  8. Choose Pricing tier section, choose Free. If additional resources are needed, the database can be scaled up at any time. To learn more on Azure SQL Pricing, read the documentation on Azure Docs.
  9. Modify collation as needed.
  10. Enter an administrator SQL Admin Username and SQL Admin Password. If you selected New SQL Database server, you aren’t entering an existing name and password here, you’re entering a new name and password that you’re defining now to use later when you access the database. If you selected a server that you created previously, you’ll enter credentials for that server.
  11. Telemetry collection can be enabled for App Service using Application Insights. Application Insights with little configuration collects valuable event, exception, dependency, request, and trace information. To learn more about Application Insights, get started in Azure Docs.
  12. Click Create at the bottom of the blade to indicate that you’re finished.

The Management Portal returns to the Dashboards page, and the Notifications blade at the top of the page shows that the site is being created. After a while (typically less than a minute), there will be a notification that the Deployment succeeded. In the navigation bar at the left, the new App Service appears in the App Services section and the new SQL Database appears in the SQL Databases section.

Deploy the application to Azure

  1. In Visual Studio, right-click the project in Solution Explorer and select Publish from the context menu.

    Publish in project context menu
  2. In the Profile tab of the Publish Web wizard, click Microsoft Azure App Service.

    Import publish settings
  3. If you have not previously added your Azure subscription in Visual Studio, perform the steps on the screen. These steps enable Visual Studio to connect to your Azure subscription so that the list of App Services will include your web site.

  4. Select the Subscription you added the App Service to, then the App Service Plan folder your App Service is a part of, and finally the App Service itself followed by Ok.

    Select App Service
  5. After the Profile has been configured, the Connection tab will be shown. Click Validate Connection to make sure that the settings are correct

    Validate connection
  6. When the connection has been validated, a green check mark is shown next to the Validate Connection button. Click Next.

    Successfully validated connection
  7. Open the Remote connection string drop-down list under SchoolContext and select the connection string for the database you created.
  8. Select Update database.

    Settings tab
    Settings tab
    This setting causes the deployment process to automatically configure the application Web.config file on the destination server so that Code First uses the MigrateDatabaseToLatestVersion initializer class.
  9. Click Next.
  10. In the Preview tab, click Start Preview.

    StartPreview button in the Preview tab
    StartPreview button in the Preview tab

The tab displays a list of the files that will be copied to the server. Displaying the preview isn’t required to publish the application but is a useful function to be aware of. In this case, you don’t need to do anything with the list of files that is displayed. The next time you deploy this application, only the files that have changed will be in this list. StartPreview file output

  1. Click Publish. Visual Studio begins the process of copying the files to the Azure server.
  2. The Output window shows what deployment actions were taken and reports successful completion of the deployment.

    Output window reporting successful deployment
  3. Upon successful deployment, the default browser automatically opens to the URL of the deployed web site. The application you created is now running in the cloud.

    Students_index_page_with_paging
    Students_index_page_with_paging

At this point your SchoolContext database has been created in the Azure SQL Database because you selected Execute Code First Migrations (runs on app start). The Web.config file in the deployed web site has been changed so that the MigrateDatabaseToLatestVersion initializer runs the first time your code reads or writes data in the database (which happened when you selected the Students tab):

The deployment process also created a new connection string (SchoolContext_DatabasePublish) for Code First Migrations to use for updating the database schema and seeding the database.

Database_Publish connection string
Database_Publish connection string

You can find the deployed version of the Web.config file on your own computer in ContosoUniversity.config. You can access the deployed Web.config file itself by using FTP. For instructions, see (xref:)ASP.NET Web Deployment using Visual Studio: Deploying a Code Update. Follow the instructions that start with “To use an FTP tool, you need three things: the FTP URL, the user name, and the password.”

[!NOTE] The web app doesn’t implement security, so anyone who finds the URL can change the data. For instructions on how to secure the web site, see Deploy a Secure ASP.NET MVC app with Membership, OAuth, and SQL Database to Azure. You can prevent other people from using the site by using the Azure Management Portal or Server Explorer in Visual Studio to stop the site.

Advanced Migrations Scenarios

If you deploy a database by running migrations automatically as shown in this tutorial, and you are deploying to a web site that runs on multiple servers, you could get multiple servers trying to run migrations at the same time. Migrations are atomic, so if two servers try to run the same migration, one will succeed and the other will fail (assuming the operations can’t be done twice). In that scenario if you want to avoid those issues, you can call migrations manually and set up your own code so that it only happens once. For more information, see Running and Scripting Migrations from Code on Rowan Miller’s blog and Migrate.exe (for executing migrations from the command line) on MSDN.

For information about other migrations scenarios, see Migrations Screencast Series.

Code First Initializers

In the deployment section you saw the MigrateDatabaseToLatestVersion initializer being used. Code First also provides other initializers, including CreateDatabaseIfNotExists (the default), DropCreateDatabaseIfModelChanges (which you used earlier) and DropCreateDatabaseAlways. The DropCreateAlways initializer can be useful for setting up conditions for unit tests. You can also write your own initializers, and you can call an initializer explicitly if you don’t want to wait until the application reads from or writes to the database. At the time this tutorial is being written in November, 2013, you can only use the Create and DropCreate initializers before you enable migrations. The Entity Framework team is working on making these initializers usable with migrations as well.

For more information about initializers, see Understanding Database Initializers in Entity Framework Code First and chapter 6 of the book Programming Entity Framework: Code First by Julie Lerman and Rowan Miller.

Summary

In this tutorial you’ve seen how to enable migrations and deploy the application. In the next tutorial you’ll begin looking at more advanced topics by expanding the data model.

Please leave feedback on how you liked this tutorial and what we could improve. You can also request new topics at Show Me How With Code.

Links to other Entity Framework resources can be found in (xref:)ASP.NET Data Access - Recommended Resources.

(xref:)Previous (xref:)Next





Comments ( )
<00>  <01>  <02>  <03>  <04>  <05>  <06>  <07>  <08>  <09>  <10>  <11>  <12>  <13>  <14>  <15>  <16>  <17>  <18>  <19>  <20>  <21>  <22>  <23
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/migrations-and-deployment-with-the-entity-framework-in-an-asp-net-mvc-application.htm
<SITEMAP>  <MVC>  <ASP>  <NET>  <DATA>  <KIOSK>  <FLEX>  <SQL>  <NOTES>  <LINUX>  <MONO>  <FREEWARE>  <DOCS>  <ENG>  <CHAT ME>  <ABOUT ME>  < THANKS ME>