Code First Migration

Source: Internet
Author: User
Tags visual studio 2010

https://msdn.microsoft.com/zh-cn/data/jj591621

Data Access and Storage > Learning > Entity Framework > Getting Started > Code First migration

This walkthrough provides an overview of the Code first migration in the Entity Framework. You can complete the walkthrough or jump to a topic of interest to you. The topics are as follows:

    • Enable migration
    • Build and run the migration
    • Custom migration
    • Data movement and custom SQL
    • Migrating to a specific version (including demotion)
    • Generate SQL Script
    • Automatic upgrade at application startup (Migratedatabasetolatestversion initializers)
Building an initial model and database

Before we start using migration, we need to have a project and a Code first model. For this walkthrough, we will still use the Blog and Post specification model.

    • to create a new Migrationsdemo Console Application
    • Add the latest version of the entityframework NuGet package to your project
      • Tools –> Library Package Manager –> Package Manager Console
      • run install-package entityframework command
    • adds a Model.cs file that contains the code shown below. This code defines a Blog class that consists of our domain model and a Blogcontext class that is the EF Code first context.




 






 





}
    • Now that we have a model, we use it to perform data access. Update the Program.cs file with the code shown below.
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;

Namespace Migrationsdemo
{
Class Program
{
static void Main (string[] args)
{
using (var db = new Blogcontext ())
{
Db. Blogs.add (New Blog {Name = "another Blog"});
Db. SaveChanges ();

foreach (var blog in db.) Blogs)
{
Console.WriteLine (blog. Name);
}
}

Console.WriteLine ("Press any key to exit ...");
Console.readkey ();
}
}
}
    • Run the application and you will see that the migrationscodedemo.blogcontext database has been created for you.
      If SQL Express is installed (included in Visual Studio 2010), the database is created in a local SQL Express instance (. \SQLExpress). If SQL Express is not installed, Code first will attempt to use LocalDb ((LocalDb) \v11.0)-LocalDb included in Visual Studio 2012.
      Note: If you have SQL Express installed, always use it first, even if you are using Visual Studio 2012


      (LOCADB database)

      (SQL Express database)
Enable migration

Now we need to make some changes to our model.

    • Let's introduce a URL attribute to the Blog class.
public string Url { get; set; }

If you plan to run the application again, InvalidOperationException is displayed, indicating that the model that supports the "Blogcontext" context has changed since the database was created. Consider migrating the update database ( http://go.microsoft.com/fwlink/?LinkId=238269) using Code first.

As indicated by the exception message, you should now start migrating with Code first. The first step is to enable migration for the context.

    • To run the enable-migrations command in the Package Manager console

This command has added the Migrations folder to the project, and this new folder contains two files:

    • Configuration class. This class allows you to configure the behavior of the migration for the context. For this walkthrough, we will use the default configuration.
      Because there is only one Code first context in your project, Enable-migrations is automatically populated with the context type to which you want to apply this configuration.
    • initialcreate Migration . This migration was generated before the migration was enabled because we had the Code first automatically create a database. The code in this scaffolding migration represents objects that have been created in the database. In this case, the class object is a Blog table that contains the BlogId and Name columns. The file name contains a timestamp, which is helpful for sorting.
      If the database has not been created, this initialcreate migration is not added to the project. Instead, the code used to create these tables will build scaffolding for the new migration when Add-migration is first called.
Build and run the migration

Code first migrates with two main commands, and you'll be familiar with them below.

    • add-migration will build scaffolding for the next migration, based on changes you made to the model since the last migration was created.
    • Update-database applies all pending migrations to the database.

We need to build scaffolding for the migration to handle the new URL properties that were previously added. Use the add-migration command to specify a name for these migrations, which we call Addblogurl.

    • Run the add-migration addblogurl command in the Package Manager console.
    • In the Migrations folder, there is now a new addblogurl migration. The migration file name is prefixed with a timestamp, which is helpful for sorting.
  namespace migrationsdemo.migrations 
{
    using System;
    using System.Data.Entity.Migrations;
    
    public partial class Addblogurl:dbmigration
     {
        public override void Up ()
     & nbsp;  {
            addcolumn ("Blogs", "Url", C = > c.string ());
       }
        
        Public override void Down ()
        {
             dropcolumn ("Blogs", "URL");
       }
   }
}

Now we can edit this migration or add content to it, everything is fine. Let's use update-database to apply this migration to the database.

    • Run the update-database command in the Package Manager console.
    • The Code first migration compares the migration in the Migrations folder to the migration that has been applied to the database. It will learn that the Addblogurl migration needs to be applied and then run the migration.

At this point, themigrationsdemo.blogcontext database has been updated with a Url column in its Blogs table. Custom migration

So far, we have generated and run the migration without making any changes. Now, let's look at how to edit the code generated by default.

    • We need to make some more changes to the model and let's add a new Rating property to the Blog class.
public int Rating { get; set; }
    • Add a new Post class






 


}
    • We also add a Posts collection to the blog class to form another layer of relationship between the blog and Post .
public virtual List<Post> Posts { get; set; }

We will use the add-migration command to have the Code first migration automatically build scaffolding for its best guess when migrating. We refer to this migration as addpostclass.

    • Run the add-migration addpostclass command in the Package Manager console.

Code first migration is doing a good job of building scaffolding for these changes, but some of the content may need to be changed:

    1. First, we add a unique index to the posts.title column
      (added to Lines 22nd and 29 of the following code).
    2. Also adds a non-nullable blogs.rating column. If there is any existing data in the table, the data is assigned the CLR default value of the new column data type (Rating is an integer, so the default value will be 0). But we want to specify a default value of 3to set a good starting level for existing rows in the Blogs table.
      (You can see the default value specified in line 24th of the following code)
Namespace Migrationscodedemo.migrations
{
Using System;
Using System.Data.Entity.Migrations;

public partial class Addpostclass:dbmigration
{
public override void Up ()
{
CreateTable (
"Posts",
c = New
{
PostID = C.int (Nullable:false, Identity:true),
Title = c.string (maxlength:200),
Content = C.string (),
BlogId = C.int (Nullable:false),
})
. PrimaryKey (t = t.postid)
. ForeignKey ("Blogs", t = T.blogid, cascadedelete:true)
. Index (t = t.blogid)
. Index (p = p.title, unique:true);

AddColumn ("Blogs", "Rating", C = C.int (Nullable:false, Defaultvalue:3));
}

public override void Down ()
{
Dropindex ("Posts", new[] {"Title"});
Dropindex ("Posts", new[] {"BlogId"});
Dropforeignkey ("Posts", "BlogId", "Blogs");
Dropcolumn ("Blogs", "Rating");
Droptable ("Posts");
}
}
}

Our edited migration is ready, let's update the database using update-database . This time specify the –Verbose tag so that you can see the SQL that the Code first migration runs.

    • Run the update-database–verbose command in the Package Manager console.
Data Movement/Custom SQL

So far, we've learned about migration operations that don't change or migrate any data, and now look at the migration that needs to move some data back and forth. There is no native support for data movement at this time, but we can run any arbitrary SQL command anywhere in the script.

    • Now add a post.abstract property to the model. We will then pre-populate the existing article with some text that starts with the Content column.
public string Abstract { get; set; }

We will use the add-migration command to have the Code first migration automatically build scaffolding for its best guess when migrating.

    • Run the add-migration addpostabstract command in the Package Manager console.
    • The resulting migration is responsible for handling schema changes, but we also want to pre-populate the Abstract column with the first 100 characters of each article's content. To do this, you can drag down to SQL and run the UPDATE statement After you add the column.
      (Added to line 12th of the following code).
Namespace Migrationscodedemo.migrations
{
Using System;
Using System.Data.Entity.Migrations;

public partial class Addpostabstract:dbmigration
{
public override void Up ()
{
AddColumn ("Posts", "Abstract", C + = c.string ());

SQL ("UPDATE Posts SET abstract = Left (Content,") WHERE Abstract is NULL ");
}

public override void Down ()
{
Dropcolumn ("Posts", "Abstract");
}
}
}

We edited a good migration very well, let's use update-database to update the database. We will specify the –Verbose tag so that you can see the SQL that is running against the database.

    • Run the update-database–verbose command in the Package Manager console.
Migrating to a specific version (including demotion)

So far, we have been upgrading to the latest migrations, but sometimes you may need to upgrade/downgrade to a specific migration.

Suppose we want to migrate the database to the state it was in when the addblogurl migration was run. You can use the –targetmigration switch to downgrade to this migration.

    • Run the update-database–targetmigration:addblogurl command in the Package Manager console.

This command will run the down script for addblogabstract and addpostclass migrations.

If you want to roll back to an empty database, you can use the update-database–targetmigration: $InitialDatabase command. Get SQL Script

If these changes are also required on other developers ' computers, after we check the changes into source control, they only need to perform a synchronous operation. After they get our new migration, you can run the Update-database command to apply these changes locally. However, if you want to push these changes to the test server and eventually to production, we might want to submit a SQL script to the DBA.

    • Run the update-database command, but specify the –script tag at this point so that the changes are written to the script without being applied. We will also specify the source and destination migrations for which the script is generated. We want the script to be used to migrate from the empty database ($InitialDatabase) to the latest version (migration addpostabstract).
      If you do not want to specify a destination migration, the migration uses the most recent migration as the destination. If you do not specify a source migration, the migration uses the current state of the database.
    • Run update-database-script-sourcemigration: $InitialDatabase-targetmigration:addpostabstract in the Package Manager console Command.

The Code first migration runs the migration pipeline instead of actually applying the changes, and it automatically writes out the changes to a. sql file. After the script is generated, it is automatically opened in Visual Studio for you to view or save. Automatic upgrade at application startup (Migratedatabasetolatestversion initializers)

If you are deploying an application, you may want to automatically upgrade the database when the application starts (by applying all pending migrations). This can be achieved by registering the migratedatabasetolatestversion database initializer. A database initializer simply contains some logic to ensure that the database is installed correctly. This logic is run the first time the context is used in the application process (AppDomain).

We can update the Program.cs file (see below), set the Blogcontext migratedatabasetolatestversion initializer First, and then use the context (line 14th). Note that you also need to add a using statement for the System.Data.Entity namespace (line 5th).

When you create an instance of this initializer, you specify the context type (Blogcontext) and the Migration configuration(configuration)-migration configuration is added to migrations when migration is enabled The class of the folder.

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Data.Entity;
Using Migrationsdemo.migrations;

Namespace Migrationsdemo
{
Class Program
{
static void Main (string[] args)
{
Database.setinitializer (New Migratedatabasetolatestversion<blogcontext, configuration> ());

using (var db = new Blogcontext ())
{
Db. Blogs.add (New Blog {Name = "another Blog"});
Db. SaveChanges ();

foreach (var blog in db.) Blogs)
{
Console.WriteLine (blog. Name);
}
}

Console.WriteLine ("Press any key to exit ...");
Console.readkey ();
}
}
}

Now, each time the application runs, it checks to see if the database being targeted is up to date, and if not, all of the pending migrations are applied. Summary

In this walkthrough, you learned how to build scaffolding, edit, and run these migrations for code-based migrations for database upgrades and demotion. In addition, you learned how to get SQL scripts to apply migrations to the database, and how to automatically apply all pending migrations when the application starts.

Code First Migration

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.