[.NET MVC4 入门系列06] 在Movie Model和表中添加新字段(Code First Migrations)

一、Entity Framework Code First 简析:

Entity Framework Code First是指,先使用Entity Framework来建立要使用Model类代码,然后由Entity Framework来为我们自动创建数据库和表。

创建过程中,Code First模式会检查数据库结构是否和Model类同步。如果不同步,Entity Framework会抛出错误。

【白话总结】

  Code First模式指的就是——现有Model类代码,然后Entity Framework自动生成对应的数据库和表。

 

二、为Model的更改设置Code First 迁移(Setting up Code First Migrations for Model Changes)

Code First 迁移(Code First Migrations):

目的、功能: 使Model类和自动生成的数据库、表同步。当Model代码更改时,通过更新数据库命令,可以生成新的和Model新类结构相一致的数据库、表。

操作步骤:

步骤1:删除原有数据库连接和数据库

        从服务器资源管理器中,找到MovieDBContext,将其删除;

        在解决方案资源管理器中,找到Movies.mdf,将其删除;

   重新生成项目

步骤2: 使用程序包管理器控制台输入命令,建立Code First Migrations

       工具——库程序包管理器——程序包管理器控制台,输入命令:

       Enable-Migrations -ContextTypeName MvcApplication1.Models.MovieDBContext

       

 

  为我们的项目开启Code First 迁移。这回同时生成一个Configuration.cs在项目的/Migrations/目录下。

步骤3:更改Configuration.cs中Seed()方法代码:

 

 1         protected override void Seed(MvcApplication1.Models.MovieDBContext context)
 2         {
 3             //  This method will be called after migrating to the latest version.
 4 
 5             //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
 6             //  to avoid creating duplicate seed data. E.g.
 7             //
 8             //    context.People.AddOrUpdate(
 9             //      p => p.FullName,
10             //      new Person { FullName = "Andrew Peters" },
11             //      new Person { FullName = "Brice Lambson" },
12             //      new Person { FullName = "Rowan Miller" }
13             //    );
14             //
15             context.Movies.AddOrUpdate(i => i.Title,
16                 new Movie
17             {
18                 Title = "When Harry Met Sally",
19                 ReleaseDate = DateTime.Parse("1989-1-11"),
20                 Genre = "Romantic Comedy",
21                 Price = 7.99M
22             },
23 
24              new Movie
25              {
26                  Title = "Ghostbusters ",
27                  ReleaseDate = DateTime.Parse("1984-3-13"),
28                  Genre = "Comedy",
29                  Price = 8.99M
30              },
31 
32              new Movie
33              {
34                  Title = "Ghostbusters 2",
35                  ReleaseDate = DateTime.Parse("1986-2-23"),
36                  Genre = "Comedy",
37                  Price = 9.99M
38              },
39 
40             new Movie
41             {
42                 Title = "Rio Bravo",
43                 ReleaseDate = DateTime.Parse("1959-4-15"),
44                 Genre = "Western",
45                 Price = 3.99M
46             });
47         }

 

这个代码在数据库被更新或新建后,被系统自动调用,用来初始化数据,提供测试用数据。注意导入命名空间:

usingMvcMovie.Models;

 重新生成项目

步骤4:生成迁移类Initial:DbMigration

  迁移类用来创建新数据库

  程序包管理器控制台中输入命令add-migration Initial

这会在/Migrations/目录下生成一个带有时间戳的Initial.cs代码,其中包含Initinal类派生自DbMigration

 

 1 namespace MvcApplication1.Migrations
 2 {
 3     using System;
 4     using System.Data.Entity.Migrations;
 5     
 6     public partial class Initial : DbMigration
 7     {
 8         public override void Up()
 9         {
10             CreateTable(
11                 "dbo.Movies",
12                 c => new
13                     {
14                         ID = c.Int(nullable: false, identity: true),
15                         Title = c.String(),
16                         ReleaseDate = c.DateTime(nullable: false),
17                         Genre = c.String(),
18                         Price = c.Decimal(nullable: false, precision: 18, scale: 2),
19                     })
20                 .PrimaryKey(t => t.ID);
21             
22         }
23         
24         public override void Down()
25         {
26             DropTable("dbo.Movies");
27         }
28     }
29 }

 

步骤5:更新数据库

  程序包管理器控制台中输入命令update-database

  这个命令会先运行步骤4中的Initial的Down和Up方法,创建新数据库;

  然后运行Seed方法添加测试数据,从而同步Model类。

 

三、为Movie类Model 添加一个Rating属性

  步骤1:更改/Model/Movie.cs ,添加Rating属性:

1   public class Movie
2     {
3         public int ID { get; set; }
4         public string Title { get; set; }
5         public DateTime ReleaseDate { get; set; }
6         public string Genre { get; set; }
7         public decimal Price { get; set; }
8         public string Rating { get; set; }
9     }

  步骤2:重新生成项目,更改View

      1)改 \Views\Movies\index.html

     

 1 @model IEnumerable<MvcMovie.Models.Movie>
 2 
 3 @{
 4     ViewBag.Title = "Index";
 5 }
 6 
 7 <h2>Index</h2>
 8 
 9 <p>
10     @Html.ActionLink("Create New", "Create")
11 </p>
12 <table>
13     <tr>
14         <th>
15             @Html.DisplayNameFor(model => model.Title)
16         </th>
17         <th>
18             @Html.DisplayNameFor(model => model.ReleaseDate)
19         </th>
20         <th>
21             @Html.DisplayNameFor(model => model.Genre)
22         </th>
23         <th>
24             @Html.DisplayNameFor(model => model.Price)
25         </th>
26          <th>
27             @Html.DisplayNameFor(model => model.Rating)
28         </th>
29         <th></th>
30     </tr>
31 
32 @foreach (var item in Model) {
33     <tr>
34         <td>
35             @Html.DisplayFor(modelItem => item.Title)
36         </td>
37         <td>
38             @Html.DisplayFor(modelItem => item.ReleaseDate)
39         </td>
40         <td>
41             @Html.DisplayFor(modelItem => item.Genre)
42         </td>
43         <td>
44             @Html.DisplayFor(modelItem => item.Price)
45         </td>
46         <td>
47             @Html.DisplayFor(modelItem => item.Rating)
48         </td>
49         <td>
50             @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
51             @Html.ActionLink("Details", "Details", new { id=item.ID }) |
52             @Html.ActionLink("Delete", "Delete", new { id=item.ID })
53         </td>
54     </tr>
55 }
56 
57 </table>

  2)改 \Views\Movies\Create.html 

 1 @model MvcApplication1.Models.Movie
 2 
 3 @{
 4     ViewBag.Title = "Create";
 5 }
 6 
 7 <h2>Create</h2>
 8 
 9 @using (Html.BeginForm()) {
10     @Html.AntiForgeryToken()
11     @Html.ValidationSummary(true)
12 
13     <fieldset>
14         <legend>Movie</legend>
15 
16         <div class="editor-label">
17             @Html.LabelFor(model => model.Title)
18         </div>
19         <div class="editor-field">
20             @Html.EditorFor(model => model.Title)
21             @Html.ValidationMessageFor(model => model.Title)
22         </div>
23 
24         <div class="editor-label">
25             @Html.LabelFor(model => model.ReleaseDate)
26         </div>
27         <div class="editor-field">
28             @Html.EditorFor(model => model.ReleaseDate)
29             @Html.ValidationMessageFor(model => model.ReleaseDate)
30         </div>
31 
32         <div class="editor-label">
33             @Html.LabelFor(model => model.Genre)
34         </div>
35         <div class="editor-field">
36             @Html.EditorFor(model => model.Genre)
37             @Html.ValidationMessageFor(model => model.Genre)
38         </div>
39 
40         <div class="editor-label">
41             @Html.LabelFor(model => model.Price)
42         </div>
43         <div class="editor-field">
44             @Html.EditorFor(model => model.Price)
45             @Html.ValidationMessageFor(model => model.Price)
46         </div>
47 
48         <div class="editor-label">
49             @Html.LabelFor(model=>model.Rating)
50         </div>
51 
52         <div class="editor-field">
53             @Html.EditorFor(model=>model.Rating)
54             @Html.ValidationMessageFor(model=>model.Rating)
55         </div>
56         <p>
57             <input type="submit" value="Create" />
58         </p>
59     </fieldset>
60 }
61 
62 <div>
63     @Html.ActionLink("Back to List", "Index")
64 </div>
65 
66 @section Scripts {
67     @Scripts.Render("~/bundles/jqueryval")
68 }

  这时,编译并运行网站,会出现一个错误:

提示MovieDBContext更改,和数据库不匹配。

可以有下面多种途径解决这个错误:

  1)使用Entity Framework 自动删除、并基于新的model class 架构 重建数据库。如果在测试数据库上使用这种方式非常方便。然而,不适合应用到已经有大量数据的数据库上,因为重建会丢失所有原有数据。

Using an initializer to automatically seed a database with test data is often a productive way to develope an application. For more information on Entity Framework database initializers, see Tom Dykstra's ASP.NET MVC/Entity Framework tutorial.

  2)更改数据库结构,以匹配model类架构。

    这种方式的优势是可以保留数据库原有记录。可以手动更改,也可以编写数据库更新脚本代码

  3)使用 Code First 迁移(Code First Migrations)来更新数据库架构。

    这时我们当前这篇博文使用的方式。

  步骤3:使用Code First Migrations 来更新数据库架构:

  1)首先打开 \Migrations\Configuration.cs 文件,为每个Movie临时对象添加Rating字段:

 1  protected override void Seed(MvcApplication1.Models.MovieDBContext context)
 2         {
 3             //  This method will be called after migrating to the latest version.
 4 
 5             //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
 6             //  to avoid creating duplicate seed data. E.g.
 7             //
 8             //    context.People.AddOrUpdate(
 9             //      p => p.FullName,
10             //      new Person { FullName = "Andrew Peters" },
11             //      new Person { FullName = "Brice Lambson" },
12             //      new Person { FullName = "Rowan Miller" }
13             //    );
14             //
15             context.Movies.AddOrUpdate(i => i.Title,
16                 new Movie
17             {
18                 Title = "When Harry Met Sally",
19                 ReleaseDate = DateTime.Parse("1989-1-11"),
20                 Genre = "Romantic Comedy",
21                 Rating = "G",
22                 Price = 7.99M
23             },
24 
25              new Movie
26              {
27                  Title = "Ghostbusters ",
28                  ReleaseDate = DateTime.Parse("1984-3-13"),
29                  Genre = "Comedy",
30                  Rating = "G",
31                  Price = 8.99M
32              },
33 
34              new Movie
35              {
36                  Title = "Ghostbusters 2",
37                  ReleaseDate = DateTime.Parse("1986-2-23"),
38                  Genre = "Comedy",
39                  Rating = "G",
40                  Price = 9.99M
41              },
42 
43             new Movie
44             {
45                 Title = "Rio Bravo",
46                 ReleaseDate = DateTime.Parse("1959-4-15"),
47                 Genre = "Western",
48                 Rating = "G",
49                 Price = 3.99M
50             });
51         }

  2)打开程序包管理器控制台中输入命令

     add-migration AddRatingMig

      如图:

   这句命令是添加一个迁移更改,并将其命名为"AddRatingMig".

  会自动检查当前的Model框架,比对数据库,生成一个加有时间戳命名的迁移代码:

   如上图,代码中包含一个Up()和Down()方法

   3)重新生成项目,并打开程序包管理器控制台中输入命令

     update-database

  更新数据库架构,如图:

  4)运行

  可以在首页(index)和create中发现新加入的Rating列

  但是Edit和Detail中还没有,那是因为我们只处理了index.cshtml和create.cshtml,读者可以自行试着模仿前面的操作改动Edit.cshtml和Detail.cshtml、SearchIndex


 

初学MS 的MVC 4,参照微软www.asp.net/mvc 中的入门项目,写个MVC 4的入门系列,以供复习和分享。

微软入门项目:http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/intro-to-aspnet-mvc-4

【目录】

1.[.NET MVC4 入门系列01]Helloworld MVC 4 第一个MVC4程序

2.  [.NET MVC4 入门系列02]MVC Movie 为项目添加Model

3.  [.NET MVC4 入门系列03]使用Controller访问Model中数据

4.  [.NET MVC4 入门系列04]Controller和View间交互原理

5. .NET MVC4 入门系列05]添加自定义查询页Search

6. [.NET MVC4 入门系列06] 在Movie Model和表中添加新字段(Code First Migrations)

7. [.NET MVC4 入门系列07] 在Model模型模块中添加验证

 

posted @ 2013-05-28 17:08  chutianshu_1981  阅读(3586)  评论(0编辑  收藏  举报