Mvc5+ef6 Getting Started complete tutorial eight

Source: Internet
Author: User

Original: Mvc5+ef6 Getting Started complete tutorial eight

This article is a relatively independent article, mainly on the non-loss of data for the database structure upgrade.

As we explained the EF features earlier (see the third article), we've covered a way to update the database:

EF compares model and database, and if both sides are inconsistent, the program will drop and re-create the database.

In this article we will use the code first migrations method.

This feature allows you to change the data model, update the structure of the database without drop and re-create the database, and deploy these changes to the production environment.

The following highlights how to use this feature.

article outline
    • Front-facing conditions
    • Enable the Migration feature
    • Perform migration
    • Summarize
front-facing conditions

Let's look back at how EF modified the model before.

We configured EF in advance to drop and re-create the database every time the data model changed.

For example, when you add, delete, or change an entity class, or change the DbContext class, when you run the program, the existing database is automatically deleted, a new database is created to match the modified model, and test data is also new based on the content of the seed method.

This method of keeping database and data model synchronized is convenient during the development phase.

If you have already deployed to a production environment, such as expanding some fields in the table, the original data cannot be lost.

We disable the way that the original database was updated, commenting out the Contexts configuration section in Web. config.

In addition, we do not use the original data, change the database name, so that a new database can be generated to facilitate the experiment.

Enable Migration

The following enables code first migrations to resolve database update issues.

    1. Open the package Manager Console

  1. Enter the following command consecutively:

    Enable-migrations and Add-migration Initialcreate

    Enable-migrations directive:

    A. A migrations folder was created under the project root directory

    B. Create a new Configuration.cs file under the Migrations folder.

    You can modify the Configuration.cs to do some configuration for migration (such as adding some test data, etc.)

    Note

    If the database name of the Web. config is not previously modified, after executing the enable-migrations instruction, migrations will find the existing database Mvcdemo and then automatically execute the add-migration instruction.

    like we talked about the DAL in the third article à AccountInitilizer.cs class, the configuration class also contains a seed method.

    This method is called when the database is new or the database structure is updated, and this method allows you to insert or update test data.

  2. Configuring the Seed method

with drop and re-create, because the database is deleted every time the model changes, all data is lost, so you need to use the Dal à AccountInitilizer.cs The Seed method to insert the test data.

Using the Code first migrations method, the test data is retained when the database changes, so the seed method containing test data is generally not required.

If we were to deploy the database to the production environment, we would not want the seed method to insert the test data into the production environment in this case.

Examples of seed methods used in production environments: for example, when we deploy, we get actual initialization data, such as the actual presence of these initialized information in the organization department.

We are doing the experiment conveniently, or inserting some test data.

Insert Sysuser and Sysrole first

As mentioned in the previous article, the seed method receives a database context parameter and uses this parameter to add a new entity to the databases.

For each entity type:

    1. Create a new Entity collection
    2. Add to the corresponding Dbset property
    3. Save changes to the database

If you remember the previous article can be found a little different, used to be the Add method, this time using the AddOrUpdate method to insert data.

Sysusers.foreach (s = = context. Sysusers.addorupdate (p = p.username, s));

The seed method executes every time the update-databse instruction is executed, and in general, after each migration, you are not just inserting data, such as the data you want to insert is already in the database after the first migration of the database you created, in which case the original data is updated.

AddOrUpdate just can solve this problem:

If the data does not exist, insert the data, and if the data exists, update the data.

Context. Sysusers.addorupdate (p = p.username, s)

The first parameter, p. Username is the primary key that checks whether the data exists.

In our test data, it is assumed that username cannot be duplicated.

As a comparison, when we add sysuserrole entity types, we do not use addorupdate, the direct human judgment exists, there is no re-insertion.

Compile the project below and start updating the database below.

Perform migration

In the previous execution of Add-migration, also in the Migrations folder, generated a <timestamp>_initialcreate.cs file.

Inside two methods, up and down:

The up method creates a database table, and the Down method deletes the table.

public override void up ()

{

CreateTable (

"dbo. Sysrole ",

c = New

{

ID = C.int (nullable: false, Identity: true),

RoleName = C.string (),

Roledesc = C.string (),

})

. PrimaryKey (t = t.id);

CreateTable (

"dbo. Sysuserrole ",

c = New

{

ID = C.int (nullable: false, Identity: true),

Sysuserid = C.int (nullable: false),

Sysroleid = C.int (nullable: false),

})

. PrimaryKey (t = t.id)

. ForeignKey ("dbo. Sysrole ", t = T.sysroleid, Cascadedelete: true)

. ForeignKey ("dbo. Sysuser ", t = T.sysuserid, Cascadedelete: true)

. Index (t = t.sysuserid)

. Index (t = t.sysroleid);

CreateTable (

"dbo. Sysuser ",

c = New

{

ID = C.int (nullable: false, Identity: true),

UserName = C.string (),

Email = C.string (),

Password = C.string (),

})

. PrimaryKey (t = t.id);

}

public override void down ()

{

Dropforeignkey ("dbo. Sysuserrole ", " Sysuserid ", " dbo. " Sysuser ");

Dropforeignkey ("dbo. Sysuserrole ", " Sysroleid ", " dbo. " Sysrole ");

Dropindex ("dbo. Sysuserrole ", new[] { " Sysroleid " });

Dropindex ("dbo. Sysuserrole ", new[] { " Sysuserid " });

Droptable ("dbo. Sysuser ");

Droptable ("dbo. Sysuserrole ");

Droptable ("dbo. Sysrole ");

}

We will perform a formal migration below. Open the package Manager Console

Input Update-database

The Update-database directive invokes the up method to create a new database table (corresponding to the data Model entity set), and then calls the seed method to populate the test data.

This time to test the next program, open the database to see, exactly in line with our expectations.

Further, we add a table test

Add a model first

Modify AccountContext.cs to add a data model entity set

Execute add-migration addtesttable and update-database to complete the database table additions.

Go to the database to check, found that the test is more than the table.

Finally, check the newly generated configuration file.

You should now be able to fully understand the effect of the documents produced by Add-migration.

Summary

This time we mainly explained the database migration/upgrade problem.

It is divided into two major steps: Enable migration (enable-migrations) and perform migration (Add-migration, update-database).

Enable migration: Generate migration-related folders migrations and related configuration files in folders.

Perform migration: produces the associated migration change file and executes the changes.

Please fully understand the examples in this article, the following article will be used many times to add-migration.

All right, here we go today.

Welcome everyone to comment, let the next article better:)

Mvc5+ef6 Getting Started complete tutorial eight

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.