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

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u012664198/article/details/91786096

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.

展开阅读全文

没有更多推荐了,返回首页