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

Source: Internet
Author: User
Tags actionlink

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

In the previous article, we learned how to use the "Code First Migrations" tool of the Entity Framework and use the "Migration" function to modify the model class, synchronously update the table structure of the corresponding database.

In this article, we will use the "Code First Migrations" tool. Use the "Send" update method to add the Rating field to each Book object and database table.

1. Add the "Rating" attribute to the Book Model


First, open the Models \ Book. cs file in Visual Studio and add a new Rating attribute to the Book class. The Code is as follows:

public string Rating { get; set; }

 

Complete Book class. The Code is as follows.

    public class Book    {        public int BookID { get; set; }        public string Category { get; set; }        public string Name { get; set; }        public int Numberofcopies { get; set; }        public int AuthorID { get; set; }        public decimal Price { get; set; }        public DateTime PublishDate { get; set; }        public string Rating { get; set; }    }

2. Use the menu "generate --> Generate solution" to generate an application. Or press CTRL-SHIFT-B.
Third, now that you have updated the model class, you also need to update it in \ Views \ Book \ Index. cshtml and \ Views \ Book \ Create. cshtml view template to display the new "Rating" attribute in the browser view.
Open the Views \ Book \ Index. cshtml file in solution manager and add a <TH> Rating </TH> column after the title of the PublishDate column. Add a <TD> column after the PublishDate column to present the Rating value. The code for the updated Index. cshtml view template is as follows:

@model IEnumerable<MvcApplication1.Models.Book>@{    ViewBag.Title = "Index";}

4. Open the "Views \ Book \ Create. cshtml" file in Solution Explorer and add the following tag near the end of the file. You can use a text box to specify a "Rating" when creating a new book ". The Code is as follows.

 

<div class="editor-label">    @Html.LabelFor(model => model.Rating)</div><div class="editor-field">    @Html.EditorFor(model => model.Rating)    @Html.ValidationMessageFor(model => model.Rating)</div>

Fifth, the application code has been updated, and the application can support the new "Rateing" attribute.
Press F5 to run the application and browse the/Book/Index URL in the browser. Now you will see the following error. For example, 1. Figure 2.

 

Figure 1

 

Figure 2

This error message is reported because the Book model class updated in the application is different from the current database's Book table architecture. (That is, the Book model class has a new attribute Rating, but the Book table in the database does not have this field. )
This error can be solved in the following ways:

1) The new model class architecture of the new entity is automatically deleted and the database is re-created by the entity architecture. This method allows you to easily create a test database. It allows you to quickly develop the database. The model and database architecture are the same. However, the disadvantage of this method is that you will lose the existing data in the database-so it is not recommended to use this method in the production environment! Using this method to automatically generate a database and insert initialized test data into the database is very convenient, and you can quickly develop applications.


2) manually modify the architecture of the existing database to match the new model class. The advantage of this method is that you can keep your existing test data. You can manually or by creating a database change script.
3. Use the "Code First Migrations" tool to update the database architecture.
In this article, we will use the "Code First Migrations" tool.
Update the "Send" method so that it provides new column values. Open the Migrations \ Configuration. cs file and add the Rating field to each Book object. The Code is as follows.

new Book         {             Name = "DB 2",             PublishDate = DateTime.Parse("1986-2-23"),               Category = "IBM",            AuthorID=1,            Numberofcopies=22,             Price = 9.99M,             Rating = "H"         }

 

6. Run menu --> tool --> Generate -- to generate a solution, and then enter the "add-migration AddRatingMig" command in the Package Manager Console window. For example.


The output is displayed in the Package Manager Console window (AddRatingMig before the timestamp will be different .)
The "add-migration" Command tells the migration framework to study the current Book model and the current Book database model, and build the necessary code to migrate the database to the new model. The AddRatingMig is arbitrary and is used to name the migration file. It helps with a meaningful name migration step.
After this command is executed, Visual Studio will open a class file of the newly defined DbMIgration derived class. You can refer to the newly created Code. The Code is as follows.

public partial class AddRatingMig : DbMigration    {        public override void Up()        {            AddColumn("dbo.Books", "Rating", c => c.String());        }                public override void Down()        {            DropColumn("dbo.Books", "Rating");        }    }

7. Run menu --> tool --> Generate -- to generate a solution, and then enter the "update-database" command in the console window of the Package Manager. For example.
The output is displayed in the Package Manager Console window (AddRatingMig before the timestamp will be different .)

Press F5 to run the application again and use the browser to browse the/Book/Index URL. You can see a new list page with a Rating field added for display. For example.

8. Click the "Create New" link and navigate to the page for adding a New book information. Note that you can add a level field on this new page.

Click "Create. A new book data, including the rating field, is now displayed in the list, for example.

 

You should also add the Rating field to the Edit, Details, and SearchIndex view templates.
You can run the "update-database" command again in the console window of the Package Manager. The input content in the window does not change because the architecture model matches.

In the eighth and ninth articles, you learned how to modify Model objects and how to update the database structure after modifying Model objects; learn how to use sample data to populate a newly created database.

 

 

Learning ASP. net mvc series:

Learning ASP. net mvc (1) -- my first ASP. net mvc application

Learning ASP. net mvc (2) -- my first ASP. net mvc Controller

Learning ASP. net mvc (3) -- my first ASP. net mvc View

Learning ASP. net mvc (4) -- my first ASP. net mvc object

Learning ASP. net mvc (5) -- my first ASP. net mvc curd page

Learning ASP. net mvc (6) -- my first ASP. net mvc editing page

Learning ASP. net mvc (7) -- my first ASP. net mvc query page

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

Learning ASP. net mvc (9) -- sample Code First Migrations

 

 

 

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.