Entity Framework Code-First(22):Code-based Migration

Code-based Migration:

Code-based migration is useful when you want more control on the migration, i.e. set default value of the column, etc.

Code-First has two commands for code based migration:

  1. Add-migration: It will scaffold the next migration for the changes you have made to your domain classes
  2. Update-database: It will apply pending changes to the database based on latest scaffolding code file you created using "Add-Migration" command

Assume that you have Student and Course entity classes initially and you want to use code-based migration for your application. Before running the commands above, you must enable migration for your application, by using the enable-migrations commands. These are in package manager that we used previously for automatic migration. This will create a configuration file, as was the case with automated migration. Also, you need to set the database initializer in the context class:

public class SchoolDBContext: DbContext
{
    public SchoolDBContext(): base("SchoolDBConnectionString")
    {
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<SchoolDBContext, SchoolDataLayer.Migrations.Configuration>("SchoolDBConnectionString"));

    }

    public DbSet<Student> Students { get; set; }
    public DbSet<Course> Courses { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

        base.OnModelCreating(modelBuilder);
    }

}

Now, you have to create a scaffold code file which consists of your database requirement from your existing domain classes. You can do this by running the “add-migration" command in the package manager. (from Tools → Library Package Manager → Package Manager Console). You will have to pass the name parameter, which will be part of the code file name.

Add-Migration command Syntax:

    Add-Migration [-Name] <String> [-Force]
      [-ProjectName <String>] [-StartUpProjectName <String>]
      [-ConfigurationTypeName <String>] [-ConnectionStringName <String>]
      [-IgnoreChanges] [<CommonParameters>]

    Add-Migration [-Name] <String> [-Force]
      [-ProjectName <String>] [-StartUpProjectName <String>]
      [-ConfigurationTypeName <String>] -ConnectionString <String>
      -ConnectionProviderName <String> [-IgnoreChanges] [<Common Parameters>]
        

You can see that this command has created a new file in the Migration folder with the name of the parameter you passed to the command with a timestamp prefix:

After creating the file above using the add-migration command, you have to update the database. You can create or update the database using the “update-database” command. You can use –verbose to see what‘s going on in the database:

Update-Database command syntax:

Update-Database [-SourceMigration <String>]
    [-TargetMigration <String>] [-Script] [-Force] [-ProjectName <String>]
    [-StartUpProjectName <String>] [-ConfigurationTypeName <String>]
    [-ConnectionStringName <String>] [<CommonParameters>]

Update-Database [-SourceMigration <String>] [-TargetMigration <String>]
    [-Script] [-Force] [-ProjectName <String>] [-StartUpProjectName <String>]
    [-ConfigurationTypeName <String>] -ConnectionString <String>
    -ConnectionProviderName <String> [<CommonParameters>]
        

At this point, the database will be created or updated.

Now, suppose you added more domain classes. So before running the application, you have to create a scaffold file for new classes, by executing the "Add-Migration" command. Once it creates the file, update the database using the Update-Database command. In this way, you have to repeat the Add-Migration and Update-Database command each time you make any changes in your domain classes.

Rollback Database change:

Suppose you want to roll back the database schema to any of the previous states, then you can use "update-database" command with –TargetMigration parameter as shown below:

update-database -TargetMigration:"First School DB schema"

Use the "get-migration" command to see what migration has been applied.

Note: Use the "get-help" command for add-migration and update-database command in order to see what parameters can be passed with this command.

时间: 2024-10-28 17:01:49

Entity Framework Code-First(22):Code-based Migration的相关文章

Entity Framework Tutorial Basics(2):What is Entity Framework?

What is Entity Framework? Writing and managing ADO.Net code for data access is a tedious and monotonous job. Microsoft has provided an O/RM framework called "Entity Framework" to automate database related activities for your application. Microso

Entity Framework Tutorial Basics(1):Introduction

以下系列文章为Entity Framework Turial Basics系列 http://www.entityframeworktutorial.net/EntityFramework5/entity-framework5-introduction.aspx ----------------------------------------------------------------------------------------------------------------------

Entity Framework Tutorial Basics(37):Lazy Loading

Lazy Loading: One of the important functions of Entity Framework is lazy loading. Lazy loading means delaying the loading of related data, until you specifically request for it. For example, Student class contains StudentAddress as a complex property

Entity Framework Tutorial Basics(36):Eager Loading

Eager Loading: Eager loading is the process whereby a query for one type of entity also loads related entities as part of the query. Eager loading is achieved using the Include() method. In the following example, it gets all the students from the dat

Entity Framework Tutorial Basics(4):Setup Entity Framework Environment

Setup Entity Framework Environment: Entity Framework 5.0 API was distributed in two places, in NuGet package and in .NET framework. The .NET framework 4.0/4.5 included EF core API, whereas EntityFramework.dll via NuGet package included EF 5.0 specifi

Entity Framework Tutorial Basics(3):Entity Framework Architecture

Entity Framework Architecture The following figure shows the overall architecture of the Entity Framework. Let us now look at the components of the architecture individually: EDM (Entity Data Model): EDM consists of three main parts - Conceptual mode

Entity Framework Tutorial Basics(42):Colored Entity

Colored Entity in Entity Framework 5.0 You can change the color of an entity in the designer so that it would be easy to see related groups of entities in the designer from Visual Studio 2012 onwards. To change the color of an entity, select entity i

Entity Framework Tutorial Basics(41):Multiple Diagrams

Multiple Diagrams in Entity Framework 5.0 Visual Studio 2012 provides a facility to split the design time visual representation of the Entity Data Model. This means that you can have multiple diagrams for one Entity Data Model. You can create a new d

Entity Framework Tutorial Basics(34):Table-Valued Function

Table-Valued Function in Entity Framework 5.0 Entity Framework 5.0 supports Table-valued functions of SQL Server. Table-valued functions are similar to stored procedure with one key difference: the result of TVF is composable which means that it can

Entity Framework Tutorial Basics(43):Download Sample Project

Download Sample Project: Download sample project for basic Entity Framework tutorials. Sample project includes SchoolDB.mdf for SQL Server 2012. It also includes SchoolDB.sql script if you are using a different version of SQL Server.