您的位置:首页 > 其它

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

2013-05-28 17:08 489 查看
一、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()方法代码:

protected override void Seed(MvcApplication1.Models.MovieDBContext context)
{
//  This method will be called after migrating to the latest version.

//  You can use the DbSet<T>.AddOrUpdate() helper extension method
//  to avoid creating duplicate seed data. E.g.
//
//    context.People.AddOrUpdate(
//      p => p.FullName,
//      new Person { FullName = "Andrew Peters" },
//      new Person { FullName = "Brice Lambson" },
//      new Person { FullName = "Rowan Miller" }
//    );
//
context.Movies.AddOrUpdate(i => i.Title,
new Movie
{
Title = "When Harry Met Sally",
ReleaseDate = DateTime.Parse("1989-1-11"),
Genre = "Romantic Comedy",
Price = 7.99M
},

new Movie
{
Title = "Ghostbusters ",
ReleaseDate = DateTime.Parse("1984-3-13"),
Genre = "Comedy",
Price = 8.99M
},

new Movie
{
Title = "Ghostbusters 2",
ReleaseDate = DateTime.Parse("1986-2-23"),
Genre = "Comedy",
Price = 9.99M
},

new Movie
{
Title = "Rio Bravo",
ReleaseDate = DateTime.Parse("1959-4-15"),
Genre = "Western",
Price = 3.99M
});
}


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

usingMvcMovie.Models;

重新生成项目

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

  迁移类用来创建新数据库

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



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

namespace MvcApplication1.Migrations
{
using System;
using System.Data.Entity.Migrations;

public partial class Initial : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Movies",
c => new
{
ID = c.Int(nullable: false, identity: true),
Title = c.String(),
ReleaseDate = c.DateTime(nullable: false),
Genre = c.String(),
Price = c.Decimal(nullable: false, precision: 18, scale: 2),
})
.PrimaryKey(t => t.ID);

}

public override void Down()
{
DropTable("dbo.Movies");
}
}
}


步骤5:更新数据库

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



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

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

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

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

public class Movie
{
public int ID { get; set; }
public string Title { get; set; }
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
public decimal Price { get; set; }
public string Rating { get; set; }
}


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

1)改 \Views\Movies\index.html

@model IEnumerable<MvcMovie.Models.Movie>

@{
ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.Title)
</th>
<th>
@Html.DisplayNameFor(model => model.ReleaseDate)
</th>
<th>
@Html.DisplayNameFor(model => model.Genre)
</th>
<th>
@Html.DisplayNameFor(model => model.Price)
</th>
<th>
@Html.DisplayNameFor(model => model.Rating)
</th>
<th></th>
</tr>

@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.ReleaseDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.Genre)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.DisplayFor(modelItem => item.Rating)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
@Html.ActionLink("Details", "Details", new { id=item.ID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.ID })
</td>
</tr>
}

</table>


  2)改 \Views\Movies\Create.html

@model MvcApplication1.Models.Movie

@{
ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)

<fieldset>
<legend>Movie</legend>

<div class="editor-label">
@Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Title)
@Html.ValidationMessageFor(model => model.Title)
</div>

<div class="editor-label">
@Html.LabelFor(model => model.ReleaseDate)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.ReleaseDate)
@Html.ValidationMessageFor(model => model.ReleaseDate)
</div>

<div class="editor-label">
@Html.LabelFor(model => model.Genre)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Genre)
@Html.ValidationMessageFor(model => model.Genre)
</div>

<div class="editor-label">
@Html.LabelFor(model => model.Price)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Price)
@Html.ValidationMessageFor(model => model.Price)
</div>

<div class="editor-label">
@Html.LabelFor(model=>model.Rating)
</div>

<div class="editor-field">
@Html.EditorFor(model=>model.Rating)
@Html.ValidationMessageFor(model=>model.Rating)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}

<div>
@Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}


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



提示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字段:

protected override void Seed(MvcApplication1.Models.MovieDBContext context)
{
//  This method will be called after migrating to the latest version.

//  You can use the DbSet<T>.AddOrUpdate() helper extension method
//  to avoid creating duplicate seed data. E.g.
//
//    context.People.AddOrUpdate(
//      p => p.FullName,
//      new Person { FullName = "Andrew Peters" },
//      new Person { FullName = "Brice Lambson" },
//      new Person { FullName = "Rowan Miller" }
//    );
//
context.Movies.AddOrUpdate(i => i.Title,
new Movie
{
Title = "When Harry Met Sally",
ReleaseDate = DateTime.Parse("1989-1-11"),
Genre = "Romantic Comedy",
Rating = "G",
Price = 7.99M
},

new Movie
{
Title = "Ghostbusters ",
ReleaseDate = DateTime.Parse("1984-3-13"),
Genre = "Comedy",
Rating = "G",
Price = 8.99M
},

new Movie
{
Title = "Ghostbusters 2",
ReleaseDate = DateTime.Parse("1986-2-23"),
Genre = "Comedy",
Rating = "G",
Price = 9.99M
},

new Movie
{
Title = "Rio Bravo",
ReleaseDate = DateTime.Parse("1959-4-15"),
Genre = "Western",
Rating = "G",
Price = 3.99M
});
}


  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模型模块中添加验证
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐