012.Adding a New Field --【添加一個新字段】

索引:html

目錄索引數據庫

Adding a New Field瀏覽器

添加一個新字段mvc

2016-10-14 3 分鐘閱讀時長 做者 app

By Rick Anderson框架

In this section you'll use Entity Framework Code First Migrations to add a new field to the model and migrate that change to the database.ide

在本節,咱們將用EF的Code First 增長一個新字段並變動到數據庫中.測試

When you use EF Code First to automatically create a database, Code First adds a table to the database to help track whether the schema of the database is in sync with the model classes it was generated from.ui

當你使用 EF Code First 自動的建立一個數據庫,Code First將會向數據庫增長一張表,他會自動追蹤數據庫結構的變化並同步結構的變化。this

If they aren't in sync, EF throws an exception. This makes it easier to find inconsistent database/code issues.

若是他們未同步,EF會拋出異常。這使得代碼與DB保持一致變得簡單。

Adding a Rating Property to the Movie Model

給 Movie 模型添加一個等級字段

Open the Models/Movie.cs file and add a Rating property:

打開 Models/Movie.cs 文件,並添加 Rating 屬性字段:

 1 public class Movie
 2 
 3 {
 4 
 5     public int ID { get; set; }
 6 
 7     public string Title { get; set; }
 8 
 9  
10 
11     [Display(Name = "Release Date")]
12 
13     [DataType(DataType.Date)]
14 
15     public DateTime ReleaseDate { get; set; }
16 
17     public string Genre { get; set; }
18 
19     public decimal Price { get; set; }
20 
21     public string Rating { get; set; }
22 
23 }
C# code

Build the app (Ctrl+Shift+B).

編譯應用。

Because you've added a new field to the Movie class, you also need to update the binding white list so this new property will be included.

由於你在 Movie 類中新增了一個字段,你須要更新綁定,這樣這個新字段才能被包含。

In MoviesController.cs, update the [Bind] attribute for both the Create and Edit action methods to include the Rating property:

MoviesController.cs 文件中,更新 Create 、 Edit 方法的 [Bind] ,以包含 Rating 屬性字段:

1 [Bind("ID,Title,ReleaseDate,Genre,Price,Rating")]
C# Code

You also need to update the view templates in order to display, create and edit the new Rating property in the browser view.

你一樣須要更新視圖模板,以便在瀏覽器上顯示,新建,編輯 Rating 字段。

Edit the /Views/Movies/Index.cshtml file and add a Rating field:

編輯 /Views/Movies/Index.cshtml 文件並增長 Rating 字段:

 1 <table class="table">
 2 
 3     <thead>
 4 
 5         <tr>
 6 
 7             <th>
 8 
 9                 @Html.DisplayNameFor(model => model.movies[0].Title)
10 
11             </th>
12 
13             <th>
14 
15                 @Html.DisplayNameFor(model => model.movies[0].ReleaseDate)
16 
17             </th>
18 
19             <th>
20 
21                 @Html.DisplayNameFor(model => model.movies[0].Genre)
22 
23             </th>
24 
25             <th>
26 
27                 @Html.DisplayNameFor(model => model.movies[0].Price)
28 
29             </th>
30 
31             <th>
32 
33                 @Html.DisplayNameFor(model => model.movies[0].Rating)
34 
35             </th>
36 
37             <th></th>
38 
39         </tr>
40 
41     </thead>
42 
43     <tbody>
44 
45         @foreach (var item in Model.movies)
46 
47         {
48 
49             <tr>
50 
51                 <td>
52 
53                     @Html.DisplayFor(modelItem => item.Title)
54 
55                 </td>
56 
57                 <td>
58 
59                     @Html.DisplayFor(modelItem => item.ReleaseDate)
60 
61                 </td>
62 
63                 <td>
64 
65                     @Html.DisplayFor(modelItem => item.Genre)
66 
67                 </td>
68 
69                 <td>
70 
71                     @Html.DisplayFor(modelItem => item.Price)
72 
73                 </td>
74 
75                 <td>
76 
77                     @Html.DisplayFor(modelItem => item.Rating)
78 
79                 </td>
80 
81                 <td>
HTML Code

Update the /Views/Movies/Create.cshtml with a Rating field.

更新 /Views/Movies/Create.cshtml 文件,增長 Rating 字段。

You can copy/paste the previous "form group" and let intelliSense help you update the fields.

你能夠 複製、粘貼 前邊的 "form group" ,並讓智能提示幫助你完成字段的更新。

IntelliSense works with Tag Helpers.

智能提示使用 Tag Helpers 來完成工做。

Note: In the RTM verison of Visual Studio 2017 you need to install the Razor Language Services for Razor intelliSense.

筆記:如今已經是 15.3.1 版本了,此句不翻譯~

This will be fixed in the next release.

此句不翻譯~

 

The app won't work until we update the DB to include the new field. If you run it now, you'll get the following SqlException:

在將 新字段包含到 DB以前 程序時不會正確運行的,他會拋出一個 SqlException 異常:

SqlException: Invalid column name 'Rating'.
TXT Code

You're seeing this error because the updated Movie model class is different than the schema of the Movie table of the existing database. (There's no Rating column in the database table.)

你將會看到錯誤,由於更新後的model不一樣於DB表的結構。

There are a few approaches to resolving the error:

下面是一些解決問題的方法:

1.Have the Entity Framework automatically drop and re-create the database based on the new model class schema.

讓EF自動刪除並基於 模型類 結構重建DB結構。

This approach is very convenient early in the development cycle when you are doing active development on a test database;

在早期的開發週期中,當你在一個測試庫上開發時這是一個很是方便的作法;

it allows you to quickly evolve the model and database schema together.

他容許你讓model與db結構一塊兒快速迭代進化。

The downside, though, is that you lose existing data in the database — so you don't want to use this approach on a production database!

這麼作的缺點是會丟失現存庫中的全部數據,在生產上咱們是不但願使用這種方法的!

Using an initializer to automatically seed a database with test data is often a productive way to develop an application.

使用初始化器來自動種植一些DB數據,是一種常使用的提升生產力的開發作法。

2.Explicitly modify the schema of the existing database so that it matches the model classes.

明確的更新已存在數據庫的結構,讓它匹配代碼中的模型類。

The advantage of this approach is that you keep your data.

這種作法的優勢是可讓你保持數據庫中已存在的數據。

You can make this change either manually or by creating a database change script.

你能夠人工的或使用腳本自動的來變動DB。

3.Use Code First Migrations to update the database schema.

使用Code First遷移來更新數據庫結構。

For this tutorial, we'll use Code First Migrations.

在本教程中,咱們會使用 Code First 遷移的作法。

Update the SeedData class so that it provides a value for the new column.

更新 SeedData 類,讓它爲新字段提供值。

A sample change is shown below, but you'll want to make this change for each new Movie.

以下是一個變動示例,你須要爲每個 new Movie 加上變化。

 1 new Movie
 2 
 3 {
 4 
 5     Title = "When Harry Met Sally",
 6 
 7     ReleaseDate = DateTime.Parse("1989-1-11"),
 8 
 9     Genre = "Romantic Comedy",
10 
11     Rating = "R",
12 
13     Price = 7.99M
14 
15 },
C# Code

Build the solution.

編譯解決方案。

From the Tools menu, select NuGet Package Manager > Package Manager Console.

Tools 菜單,選擇 NuGet Package Manager > Package Manager Console 子菜單:

 

In the PMC, enter the following commands:

在 PMC 中,鍵入如下命令:

1 Add-Migration Rating
2 
3 Update-Database
Bash Code

The Add-Migration command tells the migration framework to examine the current Movie model with the current Movie DB schema and create the necessary code to migrate the DB to the new model.

Add-Migration 命令告訴 遷移框架 檢查當前的 Movie 類並與DB結構作比較並建立出合適的代碼更新數據庫使其匹配新的model類。

The name "Rating" is arbitrary and is used to name the migration file.

"Rating" 是任意命名的,它被用來命名遷移文件名。

It's helpful to use a meaningful name for the migration file.

使用有意義的名字命名遷移文件是很是有益的。

If you delete all the records in the DB, the initialize will seed the DB and include the Rating field.

若是你刪除了DB中的數據記錄,初始化類將從新種植DB幷包含 Rating 字段。

You can do this with the delete links in the browser or from SSOX.

你能夠在瀏覽器上的刪除連接或在 SSOX 管理器界面上這麼作。

Run the app and verify you can create/edit/display movies with a Rating field.

運行程序並檢查你能夠對movie增刪改查新的 Rating 字段。

You should also add the Rating field to the Edit, Details, and Delete view templates.

你一樣應該在 Edit, Details, and Delete 視圖模板上增長 Rating 字段。

 

 

                                         蒙

                                    2017-08-22 11:22 週二

相關文章
相關標籤/搜索