Build the application to make sure there are no errors.

From the Tools menu, click Library Package Manager and then Package Manager Console.

In the Package Manager Console window at the PM> prompt enter "Enable-Migrations -ContextTypeName MvcMovie.Models.MovieDBContext".


The Enable-Migrations command (shown above) creates a Configuration.cs file in a new Migrations folder.


Visual Studio opens the Configuration.cs file. 


The next step is to create a DbMigration class for the initial migration. This migration to creates a new database, that's why you deleted the movie.mdf file in a previous step.

In the Package Manager Console window, enter the command "add-migration Initial" to create the initial migration.  The name "Initial" is arbitrary and is used to name the migration file created.

Code First Migrations creates another class file in the Migrations folder (with the name {DateStamp}_Initial.cs ), and this class contains code that creates the database schema. The migration filename is pre-fixed with a timestamp to help with ordering.  Examine the {DateStamp}_Initial.cs  file, it contains the instructions to create the Movies table for the Movie DB. When you update the database in the instructions below, this {DateStamp}_Initial.cs  file will run and create the the DB schema. Then the Seed method will run to populate the DB with test data.


_ueditor_page_break_tag_

In the Package Manager Console, enter the command "update-database" to create the database and run theSeed method.

例子:

键入“get-help NuGet”以查看所有可用的 NuGet 命令。
PM> Enable-Migrations -ContextTypeName ULBlog.Models.ULBlogDBContext
正在检查上下文的目标是否为现有数据库...
已为项目 ULBlog 启用 Code First 迁移。
PM> update-database
指定“-Verbose”标志以查看应用于目标数据库的 SQL 语句。
没有挂起的显式迁移。
无法将数据库更新为与当前模型匹配,因为存在挂起的更改并且禁用了自动迁移。将挂起的模型更改写入基于代码的迁移或启用自动迁移。将 DbMigrationsConfiguration.AutomaticMigrationsEnabled 设置为 true 以启用自动迁移。
您可使用 Add-Migration 命令将挂起的模型更改写入基于代码的迁移。
PM> add-migration Initial正在为迁移“Initial”搭建基架。
此迁移文件的设计器代码包含当前 Code First 模型的快照。在下一次搭建迁移基架时,将使用此快照计算对模型的更改。如果对要包含在此迁移中的模型进行其他更改,则您可通过再次运行“Add-Migration Initial”重新搭建基架。
PM> update-database
指定“-Verbose”标志以查看应用于目标数据库的 SQL 语句。
正在应用显式迁移: [201405190940230_Initial]。
正在应用显式迁移: 201405190940230_Initial。
正在运行 Seed 方法。
PM>

参考:http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-new-field-to-the-movie-model-and-table

?

后续修改:

We will us migrations to update the scheam. Build the solution, and then open the Package Manager Consolewindow and enter the following commands:

add-migration AddDataAnnotationsMig
update-database


最后修改:2014 年 05 月 20 日
如果觉得我的文章对你有用,请随意赞赏