ef-using migration technology to automatically update the database table structure

Source: Internet
Author: User

To undertake the previous article: on the entityframework of the class library Codefirst (code first) operation analysis

This article describes how to use migration techniques to automatically map the model entity class structure to an existing database through an ORM framework, and to add or modify the corresponding table structure.

Regardless of acceptance, use the Package Manager console in Visual Studio to execute the associated command.

1. Use "Package Manager Console"

Tools NuGet Package Manager Package Manager console

The interface of the goods is like this:

Select the default project as the DAL, as we have installed the EntityFramework package in the DAL project. Input command enable-migrations, the case does not matter, all can. The command means: Activate the migration, which is the automatic migration technology in the activation program. This command is valid only in projects where the EntityFramework package is installed. If you do not install the EntityFramework package successfully, you cannot use the command and an error occurs.

Activate the successful migration interface such as:

After the successful migration of the DAL Project, a migrations folder is automatically generated under the project, containing a sealed migration configuration class and a class that is generated using the current time, which contains the table structure that already exists in the database before the modification.

2. Migration configuration

Open the Configuration.cs file under the Migrations folder in the Dal project. Change the constructor of the configuration class to the following code:

         Public configuration () {            // set automaticmigrationsenabled True to enable automatic migration technology            True ;             // set automaticmigrationdatalossallowed to true to allow data loss when data table structure is updated            true ;             " DAL. Democontext";        }

If the configuration is not in the same assembly as the application, you need to change the configuration class's access modifier from internal to public. This allows the configuration class to be used in the application.

3. Use migration

In the main method of the console application, add Database.setinitializer (new Migratedatabasetolatestversion<democontext, DAL. Migrations.configuration> ()). As shown in the following:

Next Run the program. Once the program runs successfully, let's compare the results.

Before the data table structure is updated:

After the data table structure is updated:

Use program to automatically update table structure successfully!

4. Attribute constraints of model class attributes

Looking at the table structure above, the maximum length for name and address is Max.

Can we customize a maximum string length? Of course!

Is it possible to automatically update to the table structure? Do you think that the article on the above is white speaking?!!

Update the student class of the model layer to add attribute constraints to certain fields. Attribute constraints are not only available in the program, but can also be automatically updated to the database. The following code:

usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel.DataAnnotations;usingSystem.ComponentModel.DataAnnotations.Schema;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceModel {//Specify table name[Table ("Student")]     Public classStudent {//Specify the primary key for the table[Key,databasegenerated (databasegeneratedoption.identity)] PublicGuid ID {Get;Set; } [MaxLength ( -, errormessage ="the maximum length of a name is 50 characters")]         Public stringName {Get;Set; } [Range (typeof(DateTime),"1900-01-01","2017-07-01")]         PublicDatetime? BirthDay {Get;Set; } [Range (1, Max, errormessage ="The age range is between 1~150岁")]         Public int? Age {Get;Set; } [MaxLength ( -, errormessage ="the maximum length of an address is 100 characters")]         Public stringAddress {Get;Set; } }}

After running the program, let's look at the table structure in the database:

The student table structure has been successfully updated.

Not surprised?

Not surprisingly?

Hi, aren't you happy?

Are you having fun?

In the Codefirst mode, we did not move the database one code, completely relies on the ORM framework to map the entity model and the database. Only in the program code to move the finger, you can easily call the database, the use of data.

ef-using migration technology to automatically update the database table structure

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.