MVC:Code First Migrations

Come from old posts in MVC:Code First Migrations , 2016-08-01

有必要先来了解一下什么叫做CodeFirstMigrations(代码先行的迁移 ):

应用程序开发领域中的代码先行(Code First)方法指的是先在代码中创建对象模型,然后按照模型生成数据库结构。这与“模型先行开发”类似,那种方式会使用Visual Studio中的EF设计器创建数据模型。Code First Migrations这种工具可以基于代码中所做的改变,以递增的方式更新已存的数据库结构。这可以按照自动或者手动的方式进行,采用哪种方式依赖于对模型所做出的更新的类型。能够自动完成的变更类型有:

  • 增加属性或者类
  • 对属性和类重命名(想要使其正常工作,需要编写一些脚本)
  • 对列(column)或者表(table)重命名,而不对属性或类重命名
  • 删除属性

在任何一种情况下,执行命令Update-Database就会自动把变更应用到数据库结构上。

对于所有其它更新,Code First Migrations会使用Add-Migration命令创建变更数据库的脚本。这些迁移操作都会保存,并加上时间戳,让我们可以回滚到数据库结构的上一个版本。除了能够对数据库结构做出变更之外,迁移操作中还可以包括用于操作数据的SQL命令。想要提交迁移操作,你只需要再次运行Update-Database命令。为了对数据库进行复制,Code First Migrations也可以使用Update-Database来创建SQL脚本:

Update-Database –TargetDatabase:"NewDatabase" –Script

1)CodeFirstMigrations

执行CodeFirstMigrations 代码先行的迁移 ,我们需要这么做:

1.打开数据迁移功能(Enable Code First Migrations)

Nuget管理器->程序包管理控制台:

Enable-Migrations -ContextTypeName MVCTest001.Models.DBContext
正在检查上下文的目标是否为现有数据库...
已为项目 MVCTest001 启用 Code First 迁移。

这里需要注意,针对旧blog没有提及的问题说明,当Context上下文不在MVC主项目中的时候,需要改变指令的语法如下:

PM> Enable-Migrations -ProjectName MVCTest001.CoreProjectXXX.Models
正在检查上下文的目标是否为现有数据库...
已为项目 MVCTest001 启用 Code First 迁移。
PM>

开启数据迁移设置完成,后续的操作都按照上述的规则来处理

2.如果尝试再次进行迁移设置指令,就会得到这样的反馈:

PM> Enable-Migrations -ContextTypeName MVCTest001.Models.DBContext
已在项目“MVCTest001”中启用迁移。若要覆盖现有迁移配置,请使用 -Force 参数。

可以发现,指令不被允许,因为迁移已经开启

3.初始化数据迁移基架,并建立时间节点

PM> add-migration Initial
正在为迁移“Initial”搭建基架。
此迁移文件的设计器代码包含当前 Code First 模型的快照。
在下一次搭建迁移基架时,将使用此快照计算对模型的更改。
如果对要包含在此迁移中的模型进行其他更改,
则您可通过再次运行“Add-Migration Initial”重新搭建基架。
PM>

提示迁移完成,并按时间创立了新类,并包含了创建数据库架构的代码

4.进行数据库架构刷新,并运行Seed方法

PM> update-database
指定“-Verbose”标志以查看应用于目标数据库的 SQL 语句。
正在应用显式迁移: [201607311640461_Initial]。
正在应用显式迁移: 201607311640461_Initial。
正在运行 Seed 方法。
PM>

迁移结束,数据库架构初始化完成

2)为数据表增加条目

1.在实体类中添加新的属性(条目)

2.在View中进行所有必要的修改,在后台同样

以添加Rating为例,比如:

public ActionResult Create([Bind(Include = "ID,Title,ReleaseDate,Genre,Price,Rating")] PersonalModel personalModel) {
......

当然可能不止一处,需要全部增补完毕

在前台部分:

<td>
            <!-- ...... -->
</td>
        <td>
            @Html.DisplayFor(modelItem => item.Rating)
        </td>

以及所有需要增补的地方

3.这时候编译运行会报错

先看两个错误,(1):

自创建数据库,支持 ‘MovieDBContext’ 上下文模型已更改。考虑使用代码第一次迁移来更新数据库 (http://go.microsoft.com/fwlink/?LinkId=238269)。

(2):

Server error in “/” application ,the model backing the “……” context has changed since the database was created……

4.解决方案

因为数据库架构和实体类已经不同,这里我们通过数据库迁移的方法来解决

首先在Seed中添加你增补的条目,比如“Rating”,每一个单元都要增补

然后记得生成解决方案

接着在Nuget管理器->程序包管理控制台的输入和输出:

PM> add-migration Rating
正在为迁移“Rating”搭建基架。
此迁移文件的设计器代码包含当前 Code First 模型的快照。
在下一次搭建迁移基架时,将使用此快照计算对模型的更改。
如果对要包含在此迁移中的模型进行其他更改,
则您可通过再次运行“Add-Migration Rating”重新搭建基架。

这里要注意,“add-migration ******”的命名是随意的,处于可读性考虑,建议要像GitHub一样为commit的命名一样来处理

这样数据库就在基架框架中更新了条目,然后只要update数据库框架:

PM> update-database
指定“-Verbose”标志以查看应用于目标数据库的 SQL 语句。
正在应用显式迁移: [201608010340559_Rating]。
正在应用显式迁移: 201608010340559_Rating。
正在运行 Seed 方法。
PM>

这样数据库刷新完成,打开网页就能正常运行了,功能当然也正常

4,754 thoughts on “MVC:Code First Migrations”

  1. Wonderful work! This is the ype of info that are supposed to be shared around the internet.

    Shame on the search engines for nott positioning this submit higher!
    Comee on over and discuss with my web site .
    Thank yyou =)

  2. Its like you learn my mind! You apppear to know soo
    much about this, such ass you wrote the book in itt or something.
    I think that you just can do with a few p.c. to force the message home a bit,
    however insteqd of that, this is wonderful blog.An excellent
    read. I’ll certainly be back.

  3. Hi, I do think this is ann excellent wweb site. I stumbledupon it 😉 I may come back once again since i have
    saved as a favorite it. Money and freedom is
    the greatest way to change, mmay you be rich and continue too
    guide other people.

  4. Schöne ruhige 1-Zimmer Wohnung / Küche / BAD / WC / SAT-TV / Internet / Waschmaschine Im Grünen gelegene, komfortable, am Ende einer Sackgasse, helle ruhige 1-Zimmerwohnung mit separatem, eigenem Eingang. Die Wohnung wurde im Mai 2018 komplett renoviert und Neu eingerichtet. Parkplatzmöglichkeiten gibt es auf der öffentlichen Straße und sind in der Regel immer vorhanden. Die Wohnung hat einen 40 Zoll Sat-TV, eine Waschmaschine, sowie Internet (Wlan) gegen eine kleine Gebühr. Ein Bügeleisen und Bügelbrett sind ebenfalls forhanden. In der Küche finden Sie neben einem Backofen mit Cerankochfeld, eine Geschirspülmaschine, einen Kühlschrank mit 4-Sterne Gefrierfach, eine Kaffeemaschine ,Wasserkocher sowie einen Toaster. Der Schoko- “laden“ Werksverkauf der Weltberühmten Marke Ritter Sport sowie das Ritter Museum und das Ritter Museums-Café erreichen sie nach ca. 450 Meter bzw. 6 Minuten zu Fuß. Für Naturliebhaber lädt der schöne Schönbuch-Wald direkt vor der Haustüre zu Spaziergängen oder Wanderungen ein. Waldenbuch liegt am Nördlichen Rand des Waldgebiets und gleichnamigen Naturparks Schönbuch ca. 17 km südlich von Stuttgart und hat ca. 8500 Einwohner. Nach Böblingen sind es ca.14 km, nach Tübingen ca. 19 km und zur Messe Stuttgart ca. 12 km. Idyllisch im Tal gelegen strahlt Waldenbuch heute mit seinen Fachwerkhäusern, Brunnen und Staffeln im historischen Altstadtkern einen ganz besonderen Charme aus. Sowohl die Stadtkirche St. Veit mit ihrem 36 Meter hohen Kirchturm als auch das wunderschöne Schloss begeistern die Gäste. 24h Check-In nach Absprache möglich Lebensmitteldiscounter wie Lidl, DM-Drogerie-Markt, Penny Markt und Getränkemarkt erreicht man zu Fuß in ca. 5 bis 20 Minuten. Durch die ruhige aber dennoch zentrale Lage der Wohnung ist man mit dem Auto in kurzer Zeit in Stuttgart, Tübingen, Esslingen, Böblingen der Outlet-Stadt Metzingen oder Sindelfingen.

  5. I was wondering if you ever thought of changing
    the layout of your blog? Its very well written; I love what yoouve got to say.
    But mmaybe yoou could a little more in the way of content so pople could
    connect with it better. Youve got an awful lot of text for only having 1 or 2 images.
    Maybe you cold space it out better?

  6. Wonderful blog! I found it while surfing around on Yahoo News.

    Do you have any ttips on how to get listed in Yahoo
    News? I’ve bwen tryung for a while but I neveer seem to get there!
    Thanks

  7. Wiith havin so much written content do you ever run into any issues of
    plagorism or coplyright infringement? My blog has a lot of completely unique content I’ve either
    authored myself orr outsourced butt it appears a lot of it iis popping it up all
    over the web without myy authorization. Do you know any solutions to help protect against content from beiong stolen? I’d
    truly appreciate it.

  8. Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point.
    You obviously know what youre talking about, why throw
    away your intelligence on just posting videos to your blog when yoou
    could be giving us sometging infformative to read?

  9. TOP !!! Beautiful quiet 1-room apartment / kitchen / bath / WC / SAT-TV / Internet / washing machine In the countryside, comfortable, at the end of a cul-de-sac, bright quiet 1-room apartment with separate, private entrance. TOP !!! The apartment was completely renovated in May 2018 and refurbished. TOP !!! Parking is available on the public road and are always available. TOP !!! The apartment has a 40 inch satellite TV, a washing machine, as well as internet (wi-fi) for a small fee. An iron and ironing board are also available. In the kitchen you will find an oven with ceramic hob, a dishwasher, a refrigerator with 4-star freezer, a coffee machine, kettle and a toaster. The chocolate “shop” factory outlet of the world-famous brand Ritter Sport as well as the Ritter Museum and the Ritter Museums-Café can be reached after about 450 meters or 6 minutes on foot. For nature lovers, the beautiful Schönbuch forest invites you right outside the front door to walks or hikes. Waldenbuch is located on the northern edge of the forest and the natural park Schönbuch about 17 km south of Stuttgart and has about 8500 inhabitants. It is about 14 km to Böblingen, 19 km to Tübingen and about 12 km to the Messe Stuttgart. Idyllically located in the valley, Waldenbuch today radiates a special charm with its half-timbered houses, fountains and seasons in the historic old town center. Both the town church of St. Veit with its 36 meter high church tower and the beautiful castle delight the guests. 24h check-in by arrangement possible Food discounters such as Lidl, DM drugstore market, penny market and beverage market can be reached on foot in about 5 to 20 minutes. Due to the quiet but central location of the apartment is by car in a short time in Stuttgart, Tübingen, Esslingen, Böblingen the outlet city Metzingen or Sindelfingen.

  10. you’re really a just riight webmaster. The web site loading velocitgy iss incredible.
    It kind of feelps that you’re doing aany unique trick.
    Moreover, Thee contengs are masterpiece. you have done a great job onn this subject!

  11. Thank you for another informative web site. The placce else maay
    just I get that kind of information written in such a perfect
    manner? I have a project that I’m just now running on, and I have been on the glance out for such info.

  12. Heey there just wanted to give you a quick hsads up and let you know
    a ffew of the pictures aren’t loading correctly.
    I’m not sure why bbut I think its a linking issue. I’ve tried it in two
    differrent browsers and both show the same outcome.

  13. andrew david strutt is a rapist and mentally ill do not trust him. R0d3nt raped 2 girls at hacker conventions andy strutt wife Sichan Li is in the United States illegally. andrew david strutt has an undiagnosed psychiatric disorder from a head injury. r0d3nt has taken money from Lebanse Intelligence Officer and recently arrested hacker and owner of Krypton Security Khalil Sehnaoui. r0d3nt accepted a hotel suite in Las Vegas in 2015, 2016, and 2017 in excess of $2,000 a night from Khalil Sehnaoui. r0d3nt wife is a former reporter and Chinese Communist Party reporter. andrew strutt wife has access to his secret material. DOB 6/3/1975 sprint phone 321-917-5986 google voice 702-514-0650 works at leidos cyber

  14. I just want to mention I am just newbie to weblog and really savored your page. Likely I’m planning to bookmark your blog post . You certainly come with fantastic well written articles. Thank you for revealing your blog.

  15. I know this if off topicc but I’m looking into starting mmy own wblog and wwas curious what
    alll is required to get set up? I’m assuming having a blog like yours would cost a pretty penny?
    I’m not very web savvy so I’m not 100% sure. Any suggestions
    oor advice would be greatly appreciated. Appreciate
    it

  16. It’s a shame you don’t have a donate button! I’d most certainly donate too thks outstanding blog!
    I suppose forr noow i’ll settle for book-marking
    and adding your RSS fered to my Gooogle account. I look forward
    to fresh updates and will share this blog with my Facebook group.

    Chat soon!

Leave a Reply

Your email address will not be published. Required fields are marked *