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

Adding a New Field

添加一个新字段

2016-10-14 3 分钟阅读时长 作者

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.

在本节,我们将用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.

当你使用 EF Code First 自动的创建一个数据库,Code First将会向数据库增加一张表,他会自动追踪数据库结构的变化并同步结构的变化。

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 周二

时间: 2024-08-07 20:42:27

012.Adding a New Field --【添加一个新字段】的相关文章

Flink资料(6) -- 如何添加一个新的Operator

false false false false EN-US ZH-CN X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:普通表格; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-parent:""; mso-padding-alt

RK平台Android4.4 添加一个新的遥控器支持以及添加特殊按键

瑞芯微平台 SDK:Android4.4 好久没写博客了,最近工作中需要在SDK中添加一个新的遥控器支持,由于自己对java代码比较头大,过程也是一波三折,整个流程其实分析下来并不难,这里做个简单的总结.也算是学习android的一个开端. 1.  遥控器红外键值到linux层的映射 安卓4.4后linux层和红外层的键值映射是在设备树中修改的,不需要在linux中修改驱动代码,直接在相应的dts文件中修改即可,首先每个遥控器都有一个usercode,按照瑞芯微方面提供的文档: 在终端中输入命令

不能因为为了添加一个新功能,影响到旧的功能

涉及到后台的, 一般都是要跟数据库打交道的大型数据量的处理问题.以类 client - server 为基础的架构, 或者变形后的架构. 客户端处理用户的输入和数据, 然后大量的客户端(多个客户端的多种数据) 反馈到服务端统一处理和协调, 然后服务端对客户端发出相应的指令.其中 后台程序 代表的就是服务端的程序. 包含以下几点:1. 网络通信,  要跟远程的client打交道,只能用网络2. 并发 和 并行处理.0.. 多个客户端可能在同一时间同时需要处理同一个类型的数据, 谁先谁后,谁的有效谁

jquery如何在li元素列表的开头添加一个新li元素

jquery如何在li元素列表的开头添加一个新li元素:本章节介绍一下如何在li元素列表的开头添加一个li元素,大家最为习惯的是使用append()函数在li元素列表后面追加一个新的li元素,下面就通过代码实例介绍一下如何实现在前面添加一个新的li元素.代码如下: <!DOCTYPE html><html> <head> <meta charset=" utf-8"> <meta name="author" co

为对象添加一个新的方法

例定义一个方法,为Date对象添加一个新的成员方法,转换为形如 y-m-d<br>h:m:s Date.prototype.stringify = function(){ var s= this.getFullYear()+'-'; s+= (this.getMonth()+1)+'-'; s+= this.getDate()+' '; s+= this.getHours()+':'; s+= this.getMinutes()+':'; s+= this.getSeconds(); retu

wince7下如何添加一个新的驱动程序

在wince7中添加一个新驱动程序的步骤:(以一个简单的led驱动为例) 1.在Solution Explorer窗口中右击platform\ZYNQ7000\src\DRIVERS目录,然后选择Add->New Sources Subproject,在弹出的Subproject Wizard对话框中选择WCE Dynamic-Link Library,并将Subproject name设置为LED.点击Next并选择An empty subproject,点击Next 并选择Add to th

Python编译器实现内幕:添加一个新语句

Python编译器实现内幕:添加一个新语句 本文尝试理解Python前端的编译实现内幕,如果仅仅是读取文档,或者查看Python的实现代码,会让人感觉迷迷糊糊的,所以我的想法是动手来做一些事情:添加一个新语句until到Python编译器实现里. 所有跟本文相关的代码,都是使用Python3.4.3版本的代码,可以从CSDN的代码托管里找到,连接如下: https://code.csdn.net/caimouse/milang/tree/master 打开上面连接下载代码,就是简单直接打包下载,

jquery如何添加一个新的元素节点

jquery如何添加一个新的元素节点: 在原生的javascript中,可以使用creatElement()函数创建一个元素节点,下面介绍一下如何用jquery创建一个元素节点. 代码如下: <script type="text/javascript"> $(function(){ $(".wrap").append("<p>蚂蚁部落</p>"); }) </script> </head>

easyui 后台页面,在Tab中的链接点击后添加一个新TAB的解决方法

1.示例1 新增一个按钮 添加点击事件 onclick="self.parent.addTab('百度','http://www.baidu.com','icon-add')" 如: <a href="javascript:void(0)" title="google" onclick="self.parent.addTab('百度','http://www.baidu.com','icon-add')">打开新T