MVC5 EF 自动创建和更新数据库

1.打开NuGet Console

路径 Tools-->NuGet Package Manager-->Package Manager Console

2.Create the configuration.cs in the Migrations folder.

Put in the "enable-migrations" in the NuGet Console

3.Add the data in the Seed method of the configuration.cs file.

    protected override void Seed(MvcMovie.Models.MovieDBContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data.
            context.Movies.AddOrUpdate(i => i.Title,
                new Movie
                {
                    Title = "When Harry Met Sally",
                    ReleaseDate = DateTime.Parse("1989-1-11"),
                    Genre = "Romantic Comedy",
                    Price = 7.99M
                },

                 new Movie
                 {
                     Title = "Ghostbusters ",
                     ReleaseDate = DateTime.Parse("1984-3-13"),
                     Genre = "Comedy",
                     Price = 8.99M
                 },

                 new Movie
                 {
                     Title = "Ghostbusters 2",
                     ReleaseDate = DateTime.Parse("1986-2-23"),
                     Genre = "Comedy",
                     Price = 9.99M
                 },

               new Movie
               {
                   Title = "Rio Bravo",
                   ReleaseDate = DateTime.Parse("1959-4-15"),
                   Genre = "Western",
                   Price = 3.99M
               }
            );

        }

4.Create the database and insert the data

rebuilt the project and put in "add-migration initial" in the NuGet console,when the process finished,  put in the "update-database" .

the mdf(data) file will be created in the App_Data folder.

5.在model中添加字段,同步更新到数据库

在NuGet Console中 输入  add-migration 字段名称,完成后,输入 update-migration.

6.在model 中添加Annotation,同步更新到数据库

在NuGet Console中 输入  add-migration annotations,完成后,输入 update-migration.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章