Learning ASP. net mvc (8) -- "Code First Migrations" tool, mvcmigrations

Source: Internet
Author: User

Learning ASP. net mvc (8) -- "Code First Migrations" tool, mvcmigrations

In this article, we will learn how to use the "Code First Migrations" (also known as the Code First feature) tool of the Entity Framework and use the "Migration" feature to modify the model class, synchronously update the table structure of the corresponding database.

By default, when you use the Code First Migrations tool of the Entity Framework, the Entity Framework automatically creates a database. The "code first function" first adds a new table to the database to track whether the database architecture is synchronized with the model class. If they are not synchronized, the Entity Framework will throw an error. In this way, developers can easily find out where the problem is located during development, while other development methods can only find where the error is wrong through fuzzy error information at runtime.

1. Set model changes for code priority migration


If you are using Visual Studio 2012, double-click the Test. mdf file from Solution Explorer to open the database management tool. Visual Studio Express For Web VS displays the database resource manager, while Visual Studio 2012 displays the server resource manager in other versions. If you are using Visual Studio 2010, use the SQL Server Object Resource Manager.
1) In Server Resource Manager> data connection (database management tools, database browsers, Server resource manager, or SQL Server Object Resource Manager), right-click developer \ sqlexpress. test. dbo, and then select Delete. For example, 1. Figure 2. Figure 1 deletes a connection, and figure 2 deletes a database.

 

Figure 1

 

 

Figure 2

2) execute menu --> tool --> Generate --> to generate a solution to ensure there are no errors.
3) from the menu-> Tools menu, click the library Package Manager-> Package Manager Console. For example.

4) Enter "Enable-Migrations-ContextTypeName MvcApplication1.Models. BookDBContext" at the ">" prompt in the "Package Manager Console" window in the form below Visual Studio ". For example.

 

5) after the Enable-Migrations command is executed (as shown in), a new "Migrations" folder is created in the project and a Configuration. cs file is created in this folder. For example.

6) Open the Configuration. cs file in Visual Studio. Use the following code to replace the Send method of the Configuration. cs file:

 

namespace MvcApplication1.Migrations{    using System;    using System.Data.Entity;    using System.Data.Entity.Migrations;    using System.Linq;    using MvcApplication1.Models;     internal sealed class Configuration : DbMigrationsConfiguration<MvcApplication1.Models.BookDBContext>    {        public Configuration()        {            AutomaticMigrationsEnabled = false;        }         protected override void Seed(MvcApplication1.Models.BookDBContext 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. E.g.            //            //    context.People.AddOrUpdate(            //      p => p.FullName,            //      new Person { FullName = "Andrew Peters" },            //      new Person { FullName = "Brice Lambson" },            //      new Person { FullName = "Rowan Miller" }            //    );            //            context.Books.AddOrUpdate(i => i.BookID,        new Book        {            Name = "When Harry Met Sally",            PublishDate = DateTime.Parse("1989-1-11"),            Category = "MS",            AuthorID=1,            Numberofcopies=12,            Price = 7.99M         },         new Book         {             Name = "Ghostbusters ",             PublishDate = DateTime.Parse("1984-3-13"),              Category = "MS",            AuthorID=1,            Numberofcopies=112,             Price = 8.99M         },         new Book         {             Name = "DB 2",             PublishDate = DateTime.Parse("1986-2-23"),               Category = "IBM",            AuthorID=1,            Numberofcopies=22,             Price = 9.99M,         }   );        }    }} 

 

7) Right-click the red wavy lines under the Book, select the "resolution" menu item in the pop-up menu, and select "MvcApplication1.Models" in the pop-up menu, as shown in.

 

After doing so, Visual Studio automatically adds the following using statement to the Code:

 

using MvcApplication1.Models;

 

 

After the "Migration" name in the "Code First Migrations" function is executed in the "Package Manager Console" window, the code will automatically call the Send method (that is, the Package Manager Console will call this method to update data in the database), and insert if the object data in the Code does not exist when executing this method, if yes, update it.

Ii. database migration
1) if you press Ctrl-Shift-B (or menu --> Generate solution) in Visual Studio to compile the project, an error that cannot be compiled will occur. For example.
2) create a DbMigration class for initial migration. Use this migration name to create a new database, which is why I deleted the Test. mdf file in the previous step.
3) In the Package Manager Console window, enter the command "dd-migration Initial" to create the Initial migration. The "Initial" is named arbitrarily and is used to name the newly created Migration file. For example.

 

 

4) The "Migration" name in the "Code First Migrations" function will create a new class file (named {DATESTAMP} _ Initial. cs), and this class already contains the code for creating the database architecture. The naming rule for Migration file names has a fixed timestamp to help sort. Check the {DATESTAMP} _ Initial. cs file, which contains the description of the database for creating the Books table. The {DATESTAMP} _ Initial. cs file will run and create a database architecture. Then run the Send method to fill in the test data for the database.
5) on the Package Manager Console, enter the command "update-database" to create a database and execute the Send method. For example, 1, Figure 2.

 

Figure 1

 

Figure 2

 

If you get an error, it indicates that the table already exists and cannot be created. It may be because you are running the application. After you delete the database, execute the update database. (For example, 1 ).

In this case, delete the Test. mdf file again, and then try the "update-database" command again. For example, 2. If an error still persists, delete the folder and content, and start the description at the top of the page (that is, delete the Test. mdf file and enable and migrate it.
6) Press F5 to run the application and browse the Books/Index URL in the browser. The data filled in the database by the Send method is displayed. For example.

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.