·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设开发 >> ASP.NET网站开发 >> ASP.NET MVC5--为数据库新增字段(涉及数据库迁移技术)

ASP.NET MVC5--为数据库新增字段(涉及数据库迁移技术)

作者:佚名      ASP.NET网站开发编辑:admin      更新时间:2022-07-23

asp.net MVC5--为数据库新增字段(涉及数据库迁移技术)

Setting up Code First Migrations for Model Changes--为模型更改做数据库迁移。

1.打开资源管理器,在App_Data文件夹下,找到movies.mdf数据库文件,如果没有看到点击显示所有文件。

2.删掉movies.mdf数据库文件,并编译项目。确保没有报错。

3.找到工具菜单栏下面的NuGet程序包管理器---程序包管理器控制台,如图所示:

4,在程序包管理器控制台中,输入:Enable-Migrations -ContextTypeName MvcMovie.Models.MovieDBContext

(注意:MvcMovie.Models.MovieDBContext 项目名.Models.项目数据上下文)

按enter键之后,可以看到:

5,数据库迁移之后,VS中自动为我们生成了一个Migrations文件夹,里面有一个Configuration.cs文件

6.打开Configuration.cs文件,引用命名空间:

using MvcMovie.Models;

然后在Seed方法中写上:

 1 PRotected override void Seed(MvcMovie.Models.MovieDBContext context) 2 { 3     context.Movies.AddOrUpdate( i => i.Title, 4         new Movie 5         { 6             Title = "When Harry Met Sally", 7             ReleaseDate = DateTime.Parse("1989-1-11"), 8             Genre = "Romantic Comedy", 9             Price = 7.99M10         },11 12          new Movie13          {14              Title = "Ghostbusters ",15              ReleaseDate = DateTime.Parse("1984-3-13"),16              Genre = "Comedy",17              Price = 8.99M18          },19 20          new Movie21          {22              Title = "Ghostbusters 2",23              ReleaseDate = DateTime.Parse("1986-2-23"),24              Genre = "Comedy",25              Price = 9.99M26          },27 28        new Movie29        {30            Title = "Rio Bravo",31            ReleaseDate = DateTime.Parse("1959-4-15"),32            Genre = "Western",33            Price = 3.99M34        }35    );36    37 }

7.Code First Migrations calls theSeedmethod after every migration (that is, callingupdate-databasein the Package Manager Console), and this method updates rows that have already been inserted, or inserts them if they don't exist yet.

这句话的意思是:在每一次数据库迁移的时候,这个seed方法都会被调用,这个方法更新已经插入的行数据,或者插入行,如果这个行数据不存在。

8.下面的方法起到了一个更新插入的作用:

1 context.Movies.AddOrUpdate(i => i.Title,2     new Movie3     {4         Title = "When Harry Met Sally",5         ReleaseDate = DateTime.Parse("1989-1-11"),6         Genre = "Romantic Comedy",7         Rating = "PG",8         Price = 7.99M9     }

9.*因为Seed方法,在每次数据库迁移的时候,都会执行。你不能仅仅是插入数据,因为你将要插入的数据,将在第一次数据库迁移结束之后,已经存在数据库中;

*更新插入的操作可以预防错误,通过阻止你,插入已经存在的数据到数据库中。但是它有个缺点:它重载了,所有你在测试项目时候改变的数据;

因为有些测试数据,你不想改变:比如,你测试的时候,改变了数据,但是你不想这个数据在数据库更新的时候,发生改变。这个时候你可以做一个新增的操作:新增一个数据库中不存在的数据。

10.看一下这句代码吧:context.Movies.AddOrUpdate(i => i.Title,这第一个传到AddOrUpdate方法的参数,指定了一个属性,用来检查是否已经存在相同的行数据,对于我这个项目来说,我这个Title,可以做为这个属性,因为它在List中每次都是唯一的;This code assumes that titiles are unique. If you manually add a duplicate title, you'll get the following exception the next time you perform a migration.

Sequence contains more than one element 我们假想Title是唯一的,如果你手动添加了重复的Title,你将会在下次数据库迁移的时候,报一个错误,了解更多,请参考链接的文章,哈哈,纯人工翻译的哦。因为博主喜欢英语,所以还是看外国人的资料学习编程了。MSDN很不错的,For more information about theAddOrUpdatemethod, seeTake care with EF 4.3 AddOrUpdate Method..11.现在我们来编译一下整个项目吧,如果这这里不编译的话,后面的步骤中将会出错误。12.The next step is to create aDbMigrationclass for the initial migration. This migration creates a new database, that's why you deleted themovie.mdffile in a previous step.这句话的意思是:我们接下来要为初始化数据库迁移,创建一个DBMigration类,这个数据库迁移创建一个新的数据库,这也就是我们前面删掉Movie.mdf文件的原因。13.在程序包管理器控制台中输入:add-migration Initial我们看到:

14.Code First Migrations creates another class file in theMigrationsfolder (with the name{DateStamp}_Initial.cs), and this class contains code that creates the database schema. The migration filename is pre-fixed with a timestamp to help with ordering. Examine the{DateStamp}_Initial.csfile, it contains the instructions to create theMoviestable for the Movie DB. When you update the database in the instructions below, this{DateStamp}_Initial.csfile will run and create the the DB schema. Then theSeedmethod will run to populate the DB with test data.

这段话的意思是:Code First迁移,在Migration文件下,创建了另外一个类(类的文件名称是:时间_Initiaal.cs),并且这个类包含了创建数据库的代码。这个文件以时间的命名方式便于排序管理。检查这个文件,它包含了怎么为MovieDB创建Moviess数据库表。当你按照下面的指令(等会我在控制器管理控制台中输入的指定),更新数据库的时候,这个文件会执行,并且创建数据库,然后这个Seed方法,也将会执行,为数据库生成测试数据。

先看看看这个文件里面的代码是啥样的吧:

 1 namespace MvcMovie.Migrations 2 { 3     using System; 4     using System.Data.Entity.Migrations; 5      6     public partial class Initial : DbMigration 7     { 8         public override void Up() 9         {10             CreateTable(11                 "dbo.Movies",12                 c => new13                     {14                         ID = c.Int(nullable: false, identity: true),15                         Title = c.String(),16                         ReleaseDate = c.DateTime(nullable: false),17                         Genre = c.String(),18                         Price = c.Decimal(nullable: false, precision: 18, scale: 2),19                     })20                 .PrimaryKey(t => t.ID);21             22         }23         24         public override void Down()25         {26             DropTable("dbo.Movies");27         }28     }29 }

同样看看我们之前的Migration里面Configuration.cs代码吧:

 1 namespace MvcMovie.Migrations 2 { 3     using MvcMovie.Models; 4     using System; 5     using System.Data.Entity; 6     using System.Data.Entity.Migrations; 7     using System.Linq; 8  9     internal sealed class Configuration : DbMigrationsConfiguration<MvcMovie.Models.MovieDBContext>10     {11         public Configuration()12         {13             AutomaticMigrationsEnabled = false;14         }15 16         protected override void Seed(MvcMovie.Models.MovieDBContext context)17         {18             context.Movies.AddOrUpdate(i => i.Title,19         new Movie20         {21             Title = "When Harry Met Sally",22             ReleaseDate = DateTime.Parse("1989-1-11"),23             Genre = "Romantic Comedy",24             Price = 7.99M25         },26 27          new Movie28          {29              Title = "Ghostbusters ",30              ReleaseDate = DateTime.Parse("1984-3-13"),31              Genre = "Comedy",32              Price = 8.99M33          },34 35          new Movie36          {37              Title = "Ghostbusters 2",38              ReleaseDate = DateTime.Parse("1986-2-23"),39              Genre = "Comedy",40              Price = 9.99M41          },42 43        new Movie44        {45            Title = "Rio Bravo",46            ReleaseDate = DateTime.Parse("1959-4-15"),47            Genre = "Western",48            Price = 3.99M49        }50    );51         }52     }53 }

现在我们在,程序包管理器控制台中输入这个指令来创建数据库,并运行seed方法:

update-database

我们可以看到:

If you get an error that indicates a table already exists and can't be created, it is probably because you ran the application after you deleted the database and before you executedupdate-database. In that case, delete theMovies.mdffile again and retry theupdate-databasecommand. If you still get an error, delete the migrations folder and contents