Code first migrations steps to update the database structure

Source: Internet
Author: User

My understanding of Codefirst, with the corresponding Modelfirst and Databasefirst, the three have their own choice according to the actual situation of the project.

1, the development process in advance design database and according to this in the project to generate *.DBML or *.edmx file, is Databasefirst;

2, the development of the first establishment of an empty *.EDMX file, the file generated by the database, is Modelfirst;

3, use System.Data.Entity. DbContext and System.Data.Entity. Dbset build the data model, there is no visual file, only the entity class, is codefirst.

Now focus on how to automatically update the database and the various problems encountered when your entity class changes in Codefirst mode. The following are some of the changes that are available to support Automatic Updates:

A. Add attributes or Classes

B. Renaming properties and classes (you need to write some scripts if you want to make them work correctly)

C, rename columns (column) or tables (table), and do not rename properties or classes

D. Delete attributes

First, open the Package Manager console

When your entity model is inconsistent with the database schema, the following error is thrown:
The model backingthe ' schoolcontext ' context has changed since, the database was created. Consider using Code first migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269)
Baidu Search Code First migrations, said to execute the command update-database, where to execute it? Keep looking, VS. NET "Package Manager Console" appeared, but the article did not say where to bring up this console. I am also a beginner, find a half-day finally know where it lives, "Jiewen console where there?" Cowboy points in view. vs.net→ "View" toolbar → other Windows → Package Manager console

Second, installation EntityFramework

Open the Package Manager console, set up the project that contains the entity model, and execute update-database if your project has only one layer, the following error may not occur. My test project puts the entity model in Mvc4dal, so it prompts "no packages are installed." The EntityFramework package isn't installed on project ' Mvc4dal '.

1. Right-click Mvc4dal project → manage nuget packages

2. Set up package source

"Failed to resolve this remote name: ' nuget.org '" appears in the interface, congratulations, you can not skip this step. Click on the "Settings" button at the bottom left

Right in the Settings window to create a new package source, enter the URL of the source "http://157.56.8.150/api/v2/" tick Enable, click "OK"

3, Installation EntityFramework

Select the package source that you just created, locate EntityFramework in the list, and install

Three, need to set up the relevant parameters

1. Set up the database connection string

In the project, locate the app. config (no manually added in the project root, where the settings are only valid for this project and do not affect the settings in the Web project). Configuration <connectionStrings> node, new <addname= "mydbconnectstring" providername= "System.Data.SqlClient" Connectionstring= "datasource=.; Initial Catalog=mydb;user id=sa;password=123456 "/>,mvc4dal is a connection string with the name mydbconnectstring

Publicclassschoolcontext:dbcontext

{

Publicschoolcontext (): Base ("mydbconnectstring")

If the connection string is not set, or if the string is incorrectly set, the following prompt will appear:
Anerror occurred while getting provider information from the database. This canbe caused by Entity Framework using an incorrect connection string. Check Theinner exceptions for details and ensure, the connection string is correct.

2. Run Command enable-migrations

You will need to perform enable-migrations when the following prompt appears:
Nomigrations configuration type is found in the assembly ' Mvc4dal '. (in VisualStudio, you can use the Enable-migrations command from package Manager Consoleto add a migrations configuration).

Open the Package Manager console, run the command enable-migrations, and the Migrations folder and the corresponding file will appear in the Mvc4dal project Configuration.cs

You may be interrupted by an error while executing enable-migrations, and you will need to run the parameter command Enable-migrations-force again:
Migrationshave already been enabled in project ' Mvc4dal '. To overwrite the existingmigrations configuration, use The-force parameter.

Note there is no space in the middle of "enable-migrations", there must be a space in front of "-force".

3. Set Automaticmigrationsenabled to True

Open the Migrations folder in the configuration.cs,automaticmigrationsenabled default to False to True, otherwise the prompt will appear:
Unable to update match the current model because there arepending changes and automatic migration are disabled. Either write the Pendingmodel changes to a code-based migration or enable automatic migration. Setdbmigrationsconfiguration.automaticmigrationsenabled to True to enableautomatic migration. You can use the add-migration command to write the Pendingmodel changes to a code-based migration.

Iv. Final implementation of Update-database

The above steps are all set up, open the "Package Manager Console", run the command update-database, no error on the merit. Note here that it is important to have a table with a name of dbo.__migrationhistory in the database, which records all updates from the creation of the database, so don't move it if you are not absolutely sure.

Code first migrations steps to update the database 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.