Learn ASP. NET MVC (eight)--"Code First migrations" tool

Source: Internet
Author: User

In this article, we learned how to use the Entity Framework's Code First migrations (also known as the Code -first feature) tool to make some modifications to the model class using the migration feature, while simultaneously updating the table structure of the corresponding database.

By default, when you use the Entity Framework's Code first migrations tool, the Entity Framework automatically creates a database. The code-ahead feature first adds a new table to the database to keep track of whether the schema of the database is synchronized with the model class. If they are not synchronized, the Entity Framework throws an error. This makes it easier for developers to track down where the problem is when they develop, while other development methods can only be used at runtime to find out what went wrong with vague error messages.

One, the model change of setting code first migration


If you are using Visual Studio 2012, double-click the Test.mdf file from Solution Explorer to open the Database administration tool. where Visual Studio Express for Web version VS will display Database Explorer,Visual Studio The other versions display the Server Resource Manager. If you are using Visual Studio , use SQL Server Object Explorer.
1) in Server Explorer-"Data Connections" (Database administration Tools, database browser, Server Explorer, or SQL Server Object Explorer), right-click Developer\sqlexpress. Test.dbo, and then select Delete. such as 1, figure 2. Figure 1 is deleting the connection, and figure 2 is deleting the database.

Figure 1

Figure 2

2) Execute the menu- -"Tools --" Generate --"to generate a solution to ensure that there are no errors.
3) from the menu --Tools menu, click the Library Package Manager --Package Manager console. Such as.

4) in the lower form of Visual Studio , in the Package Manager Console window,in the>prompt, enter Enable-migrations-contexttypename MvcApplication1.Models.BookDBContext ". Such as.

5) After executing the enable-migrations command (as shown in), a new folder "Migrations" is created in the project and a Configuration.cs file is created in this folder . Such as.

6) open the Configuration.cs file in Visual Studio . Replace the Send method of the Configuration.cs file with the following code:

namespacemvcapplication1.migrations{usingSystem; usingSystem.Data.Entity; usingSystem.Data.Entity.Migrations; usingSystem.Linq; usingMvcapplication1.models; Internal Sealed classConfiguration:dbmigrationsconfiguration<mvcapplication1.models.bookdbcontext>    {         PublicConfiguration () {automaticmigrationsenabled=false; }         protected Override voidSeed (MvcApplication1.Models.BookDBContext context) {//This method is 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,NewBook {Name="When Harry Met Sally", Publishdate= DateTime.Parse ("1989-1-11"), Category="MS", Authorid=1, NumberOfCopies= A, Price=7.99M         },         NewBook {Name="Ghostbusters", Publishdate= DateTime.Parse ("1984-3-13"), Category="MS", Authorid=1, NumberOfCopies= the, Price=8.99M         },         NewBook {Name="DB 2", Publishdate= DateTime.Parse ("1986-2-23"), Category="IBM", Authorid=1, NumberOfCopies= A, Price=9.99M,         }   ); }    }} 

7) Right-click the red wavy line under book, select the "Parse" menu item in the pop-up menu, and select "mvcapplication1.models " in the pop-up menu. " ; such as.

After doing so, Visual studio automatically adds the using statement in your code as follows:

using Mvcapplication1.models;

After you have executed the "migrate" name in the "Code First migrations" function in the Package Manager console window, the code automatically calls the Send method (that is, the Package Manager console calls this method to update the data in the database). And when the method is executed, if the object data in the code does not exist, it is inserted and is updated if it exists.

Ii. migrating the database
       1)   visual studio Press ctrl-shift-b (or menu-- build Solution) to compile the project, there will be errors that cannot be compiled. Such as.  
dbmigration file.  
       3)   In the Package Manager Console window, enter the command "dd-migration initial" to create the initial migration. Where the name "Initial" is arbitrary, it is used to name the newly created migration file. Such as.

4) The "Migration" name in the "Code first migrations" feature creates a new class file (named {Datestamp}_initial.cs) in the Migration folder, and this class already contains the Create The code for the database schema. There is a fixed timestamp in the naming convention for migrating file names to help with sorting. Examine The {datestamp}_initial.cs file, which contains a description of the database that created the Books table. This {datestamp}_initial.cs file will run and create the database schema. Then run the Send method to populate the database with the test data.
5) In the Package Manager console, enter the command "Update-database" to create the database and execute the Send method. such as 1, figure 2.

Figure 1

Figure 2

If you get an error indicating that the table already exists and cannot be created, it may be because you are running the application before you execute the update database after you delete the database. (e.g. 1).

In this case, delete the test.mdf file again, and then retry the "update-database" command. such as 2. If the error still occurs, delete the folder and the content, and then start the description at the top of the page (that is, delete the Test.mdf file and then enable, migrate).
6) Press F5 to run the application and browse the Books/index URL in the browser. The data that is populated in the database is displayed in the Send method. Such as.

Learn ASP. NET MVC (eight)--"Code First migrations" tool

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.