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

 

 

 

 

转载于:https://www.cnblogs.com/Meng-NET/p/7410756.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/268614.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

system.gc()和system.runFinalization()区别作用

system.gc()和system.runFinalization()区别作用&#xff1a; System.gc(); //告诉垃圾收集器打算进行垃圾收集&#xff0c;而垃圾收集器进不进行收集是不确定的 System.runFinalization(); //强制调用已经失去引用的对象的finalize方法

路径依赖”理论

“路径依赖”理论&#xff1a;好的开始是成功的一半第一个明确提出“路径依赖”理论的是美国经济学家道格拉斯诺思。诺思认为&#xff0c;“路径依赖”类似于物理学中的“惯性”&#xff0c;一旦进入某一路径&#xff08;无论是“好”的还是“坏”的&#xff09;就可能对这种路…

Linux中xml导入数据库,XML数据库 BaseX

BaseX 是一个XML数据库&#xff0c;用来存储紧缩的XML数据&#xff0c;提供了高效的 XPath 和 XQuery 的实现&#xff0c;还包括一个前端操作界面。BaseX是一个非常轻巧和高性能的XML数据库系统和XPath/XQuery处理。包含了对W3C Update和Full Text扩展的全面支持。一个可交互和…

HDU6168 Numbers

题意&#xff1a;一个序列由原序列的任意两个数相加得到&#xff0c;给出新序列&#xff0c;求原序列 题解&#xff1a;找到最小的两个值就是原序列的最小的两个&#xff0c;删掉两个数的和&#xff0c;重复上面步骤 #include <bits/stdc.h> #define ll long long #defin…

redhat Enterprise 5下安装中文输入法,

redhat Enterprise 5下安装中文输入法&#xff0c;这实际上次解决VMware 6.5下不能正确显示中文的第二部分吧&#xff0c;还是以前的老问题&#xff0c;VMware6.5下安装redhat Enterprise linux5 过程中完全是自动安装&#xff0c;没有选项&#xff0c;装完之后是中文版&#x…

linux教程opensuse,OpenSUSE/Linux 网络配置

因工作需要&#xff0c;接触到了一台OpenSUSE系统的Linu服务器&#xff0c;开始以为和CentOS一样只需要配置一个ifcfg-ethx文件即可&#xff0c;但是配置后却发现根本没有网络&#xff0c;遂去查询相关资料&#xff0c;OpenSUSE系统的网络设置如下&#xff1a;一、修改ifcfg-et…

C++学习点滴

最近加入一个C的学习群&#xff0c;群里免不了有些网友提问题。我也正好学习一下。把一些问题&#xff0c;一些小程序记录下来&#xff0c;让自己的C水平慢慢提上来...... 函数功能&#xff1a; 把输入的字符串中的标点符号去掉之后输出来&#xff0c;循环执行 如果输入的字符串…

Flume协作框架

Flume协作框架 1.概述   -》flume的三大功能    collecting, aggregating, and moving       收集 聚合 移动 2.框图 3.架构特点  -》on streaming data flows    基于流式的数据    数据流&#xff1a;job-》不断获取数据    任务流&#xff1a;job…

linux history操作的路径,绝对路径和相对路径,目录命令(cd,mkdir,rm,history)

绝对路径和相对路径绝对路径是以/(根)开头的[rootaminglinux-02 ~]# ls /etc/hostname/etc/hostname相对路劲是相对当前目录的路径[rootaminglinux-02 ~]# pwd 查看当前目录/root[rootaminglinux-02 ~]# ls .ssh/authorized_keys.ssh/authorized_keyscd 命令cd进入目录&#xf…

【iCore4 双核心板_FPGA】例程八:乘法器实验——乘法器使用

实验现象&#xff1a; 程序运行时&#xff0c;绿色led闪烁&#xff08;目前&#xff0c;具体的乘法器调用请参考iCore3乘法器例程&#xff09; 核心代码&#xff1a; module multiplier_ctrl(input clk_25m,input rst_n,output fpga_ledg ); //--------------------clk_10hz---…

如何通过编程方式添加Native Client服务器别名

之前我有一篇博客讲到了Native Client中添加服务器别名的问题。请参考下面的链接&#xff08;讨论服务器别名的内容在该链接文章的底部&#xff09; http://www.cnblogs.com/chenxizhang/archive/2009/04/23/1441913.html 我当时是想直接改注册表的方式。这种方式当然肯定是可…

windows os x linux,What languages are Windows, Mac OS X and Linux written in?

问题I was just wondering who knows what programming languages Windows, Mac OS X and Linux are made up from and what languages are used for each part of the OS (ie: Kernel, plug-in architecture, GUI components, etc).I assume that there are multiple language…

Windows 7 硬盘安装方法

Windows 7硬盘安装正确方法收集一早同事的Windows 7系统有点问题&#xff0c;视频等不能正常播放。想要升级到7068的比较新的版本&#xff0c;是修复呢&#xff0c;还是重新安装呢&#xff1f;但他没有光驱&#xff0c;只能硬盘安装了。于是网上收集了一些硬盘安装的资料。这三…

Jmeter常见问题

1. JMeter的工作原理是什么&#xff1f;向服务器提交请求&#xff1b;从服务器取回请求返回的结果。2. JMeter的作用&#xff1f;JMeter可以用于测试静态或者动态资源的性能&#xff08;文件、Servlets、Perl脚本、java对象、数据库和查询、ftp服务器或者其他的资源&#xff…

linux7.0开启ssh端口命令,Centos 7 修改SSH端口号

最近自己需要用台linux服务器&#xff0c;听朋友意见选择了Centos&#xff0c;安装完了之后发现全是坑&#xff01;防火墙改为firewalld&#xff0c;linux系统默认了10多年的iptables都没装。。。预装的数据库是mariadb&#xff0c;没有mysql(后来查资料mariadb是mysql的分支&a…