EF Code First Migrations database migration, efmigrations

Source: Internet
Author: User

EF Code First Migrations database migration, efmigrations
1. EF Code First creates a database

Step 1: Create a console application

Step 2: Install EntityFramework

Run the following statement on the Package Manager Console:

PM> Install-Package EntityFramework

2. Project Structure

Two entities and ing. The PortalContext code is as follows:

using System;using System.Collections.Generic;using System.Data.Common;using System.Data.Entity;using System.Linq;using System.Text;using System.Threading.Tasks;using Portal.Enities;using Portal.Mapping;namespace Portal{    public class PortalContext : DbContext    {        static PortalContext()        {            System.Data.Entity.Database.SetInitializer<PortalContext>(null);           //Database.SetInitializer(new DropCreateDatabaseAlways<PortalContext>());        }        public DbSet<Category> Categories { get; set; }        public DbSet<Province> Provinces { get; set; }        /// <summary>        /// This method is called when the model for a derived context has been initialized, but        /// before the model has been locked down and used to initialize the context.  The default        /// implementation of this method does nothing, but it can be overridden in a derived class        /// such that the model can be further configured before it is locked down.        /// </summary>        /// <remarks>        /// Typically, this method is called only once when the first instance of a derived context        /// is created.  The model for that context is then cached and is for all further instances of        /// the context in the app domain.  This caching can be disabled by setting the ModelCaching        /// property on the given ModelBuidler, but note that this can seriously degrade performance.        /// More control over caching is provided through use of the DbModelBuilder and DbContextFactory        /// classes directly.        /// </remarks>        /// <param name="modelBuilder"> The builder that defines the model for the context being created. </param>        protected override void OnModelCreating(DbModelBuilder modelBuilder)        {            modelBuilder.Configurations.Add(new CategoryMap());            modelBuilder.Configurations.Add(new ProvinceMap());        }    }}

Other codes can be downloaded from the end of this blog.

3. EF Code First database migration

Step 1: generate a database

Modify the static constructor of PortailContext. cs to cancel the settings of the current database reconstruction database when the database model changes.

static PortalContext()        {            System.Data.Entity.Database.SetInitializer<PortalContext>(null);            //Database.SetInitializer(new DropCreateDatabaseAlways<PortalContext>());        }

Step 2: On the Package Manager Console, execute the following statement:

PM> Enable-Migrations-EnableAutomaticMigrations

The running result is as follows:

The Configuration code is as follows:

namespace Portal.Migrations{    using System;    using System.Data.Entity;    using System.Data.Entity.Migrations;    using System.Linq;    internal sealed class Configuration : DbMigrationsConfiguration<Portal.PortalContext>    {        public Configuration()        {            AutomaticMigrationsEnabled = true;        }        protected override void Seed(Portal.PortalContext context)        {            //  This method will be 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" }            //    );            //        }    }}

Step 3: run the following statement on the Package Manager Console:

PM> Add-Migration InitialCreate

The running result is as follows:

Step 4: run the following statement on the Package Manager Console:

PM> Update-Database-Verbose

The execution result is as follows:

At this point, the data has been created:

4. EF Code First adds an object

Step 1: add the City. cs entity

Step 2: run the following statement on the Package Manager Console:

PM> Add-Migration AddCity

The execution result is as follows:

Step 3: update the object to the database and execute the following statement on the Package Manager Console

PM> Update-Database-Verbose

Database changes are as follows:

5. EF Code First modifies an object

Step 1: Modify the City and add the CityNo attribute

Step 2: run the following code in the Package Manager Console:

PM> Add-Migration UpdateCity

The execution result is as follows:

Step 3: run the following statement on the Package Manager Console:

PM> Update-Database-Verbose

The execution result is as follows:

6. Version Tracing

Step 1: Modify the City in the database and delete the CityNo Field

Step 2: run the following statement on the package manager controller:

PM> Add-Migration ModifyCity

Step 3: update to the database and run the following statement on the Package Manager Console:

PM> Update-Database-Verbose

Run the following statement on the Package Manager Console:

PM> Update-Database-SourceMigration "201701_1349455_addcity.cs"

The execution result is as follows:

7. Other commands

1. enable database migration for the specified DbContext

PM> Enable-Migrations -ContextTypeName Portal.PortalContext
2. Set whether automatic migration is allowed
Enable-Migrations

Constructor of the generated Configuration. cs File

public Configuration(){      AutomaticMigrationsEnabled = false;}

3. Enable-Migrations specifies the project name

PM>Enable-Migrations -StartUpProjectName Portal

If the default project is selected in the "Package Manager Console", you can not set the "-StartUpProjectName" parameter. If you execute this command multiple times, you can add the-Force parameter.

4. view the executed SQL statement-Verbose command

Update-Database -Verbose 
8. Sample download

Portal sample download: http://files.cnblogs.com/files/zsy/Portal.rar

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.