Home Database Mysql Tutorial EF Code First Migrations数据库迁移

EF Code First Migrations数据库迁移

Jun 07, 2016 pm 02:59 PM
c code first database migrate

1、EF Code First创建数据库 新建控制台应用程序Portal,通过程序包管理器控制台添加EntityFramework。 在程序包管理器控制台中执行以下语句,安装EntityFramework。 PM Install-Package EntityFramework 安装成功后,界面提示如下图: 在新建的Portal控制台

1、EF Code First创建数据库

  新建控制台应用程序Portal,通过程序包管理器控制台添加EntityFramework。

  在程序包管理器控制台中执行以下语句,安装EntityFramework。

PM> Install-Package EntityFramework
Copy after login

  安装成功后,界面提示如下图:

EF Code First Migrations数据库迁移

   在新建的Portal控制台应用程序中添加两个实体类,代码结构如下:

EF Code First Migrations数据库迁移

  其中,类文件PortalContext.cs的代码如下:

<span>using</span><span> System;
</span><span>using</span><span> System.Collections.Generic;
</span><span>using</span><span> System.Linq;
</span><span>using</span><span> System.Text;

</span><span>using</span><span> System.Data.Entity;
</span><span>using</span><span> System.Data.Entity.Infrastructure;

</span><span>using</span><span> Portal.Entities;
</span><span>using</span><span> Portal.Mapping;

</span><span>namespace</span><span> Portal
{
    </span><span>public</span> <span>class</span><span> PortalContext : DbContext
    {
        </span><span>static</span><span> PortalContext()
        {
            Database.SetInitializer(</span><span>new</span> DropCreateDatabaseIfModelChanges<portalcontext><span>());
        }

        </span><span>public</span> DbSet<province> Provinces { <span>get</span>; <span>set</span><span>; }
        </span><span>public</span> DbSet<category> Categories { <span>get</span>; <span>set</span><span>; }

        </span><span>protected</span> <span>override</span> <span>void</span><span> OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(</span><span>new</span><span> ProvinceMap());
            modelBuilder.Configurations.Add(</span><span>new</span><span> CategoryMap());
        }
    }
}</span></category></province></portalcontext>
Copy after login

  在静态构造函数中,设置了当数据库模型发生改变时,则删除当前数据库,重建新的数据库。

  代码执行后,生成的数据库:

 EF Code First Migrations数据库迁移

2、EF Code First数据库迁移

2.1、生成数据库

  修改类文件PortalContext.cs的静态构造函数,取消当数据库模型发生改变时删除当前数据库重建新数据库的设置。

<span>static</span><span> PortalContext()
{
    Database.SetInitializer</span><portalcontext>(<span>null</span><span>);
}</span></portalcontext>
Copy after login

   1>、在程序包管理器控制台,执行语句:

PM> Enable-Migrations -EnableAutomaticMigrations
Copy after login

 EF Code First Migrations数据库迁移

  执行成功后,Portal控制台应用程序代码结构中,添加Migrations文件夹,并生成类文件Configuration.cs。

EF Code First Migrations数据库迁移

<span>namespace</span><span> Portal.Migrations
{
    </span><span>using</span><span> System;
    </span><span>using</span><span> System.Data.Entity;
    </span><span>using</span><span> System.Data.Entity.Migrations;
    </span><span>using</span><span> System.Linq;

    </span><span>internal</span> <span>sealed</span> <span>class</span> Configuration : DbMigrationsConfiguration<portal.portalcontext><span>
    {
        </span><span>public</span><span> Configuration()
        {
            AutomaticMigrationsEnabled </span>= <span>true</span><span>;
        }

        </span><span>protected</span> <span>override</span> <span>void</span><span> Seed(Portal.PortalContext context)
        {
            </span><span>//</span><span>  This method will be called after migrating to the latest version.

            </span><span>//</span><span>  You can use the DbSet<t>.AddOrUpdate() helper extension method 
            </t></span><span>//</span><span>  to avoid creating duplicate seed data. E.g.
            </span><span>//</span>
            <span>//</span><span>    context.People.AddOrUpdate(
            </span><span>//</span><span>      p => p.FullName,
            </span><span>//</span><span>      new Person { FullName = "Andrew Peters" },
            </span><span>//</span><span>      new Person { FullName = "Brice Lambson" },
            </span><span>//</span><span>      new Person { FullName = "Rowan Miller" }
            </span><span>//</span><span>    );
            </span><span>//
</span><span>        }
    }
}</span></portal.portalcontext>
Copy after login

   2>、在程序包管理器控制台,执行语句:

PM> Add-Migration InitialCreate
Copy after login

EF Code First Migrations数据库迁移

  执行成功后,在Migrations文件夹中新增类文件201309201556388_InitialCreate.cs

EF Code First Migrations数据库迁移

  3>、在程序包管理器控制台,执行语句:

PM> Update-Database -Verbose
Copy after login
Copy after login
Copy after login

  执行结果生成与上面一致的数据库

EF Code First Migrations数据库迁移

  4>、在数据库模型中添加City类,执行程序包管理器控制台语句,Migrations文件夹中新增类文件201309201643300_AddCity.cs。

PM> Add-Migration AddCity
Copy after login

  再次执行程序包管理器控制台语句

PM> Update-Database -Verbose
Copy after login
Copy after login
Copy after login

EF Code First Migrations数据库迁移

  Portal控制台应用程序的代码结构:

EF Code First Migrations数据库迁移

  数据库更新成功之后,在数据库中新增表City。

EF Code First Migrations数据库迁移

2.2、版本回溯

  修改数据库中表City,删除其中字段ProvinceNo。在程序包管理器控制台中执行以下两条语句:

PM> Add-Migration ModifyCity
Copy after login

PM> Update-Database -Verbose
Copy after login
Copy after login
Copy after login

  执行成功之后,City表结构修改为:

EF Code First Migrations数据库迁移

  执行程序包管理器控制台语句,进行数据库版本回溯。

PM> Update-Database –TargetMigration:<span>"</span><span>201309201643300_AddCity.cs</span><span>"</span>
Copy after login

2.3、生成数据库版本之间的Sql脚本

  执行程序包管理器控制台语句,生成数据库版本之间的Sql脚本。该操作仅为生成Sql语句,并未在数据库中进行执行。

Update-Database -Script -SourceMigration:<span>"</span><span>201309201643300_AddCity.cs</span><span>"</span> -TargetMigration:<span>"</span><span>201309201708043_ModifyCity.cs</span><span>"</span> 
Copy after login

  其中-TargetMigration在未指定的情况,默认为迁移到最新的版本。

3、EF Code First Migrations语句的其他参数

1>、为指定的DbContext启用数据库迁移

PM> Enable-Migrations -ContextTypeName Portal.PortalContext
Copy after login

2>、设置是否允许自动迁移

Enable-Migrations
Copy after login

生成的Configuration.cs类文件的构造函数

<span>public</span><span> Configuration()
{
      AutomaticMigrationsEnabled </span>= <span>false</span><span>;
}</span>
Copy after login

3>、Enable-Migrations指定项目名称

PM> Enable-Migrations -StartUpProjectName Portal
Copy after login

如果在“Package Manager Console”中选择了默认项目可以不设置“-StartUpProjectName”参数;如果多次执行此命令可以添加-Force参数。

4>、查看所执行的Sql语句 -Verbose指令

Update-Database -Verbose 
Copy after login

4、代码下载

Portal.zip

5、参考资料

http://msdn.microsoft.com/en-US/data/jj591621

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos Jul 18, 2024 am 05:48 AM

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

Detailed tutorial on establishing a database connection using MySQLi in PHP Detailed tutorial on establishing a database connection using MySQLi in PHP Jun 04, 2024 pm 01:42 PM

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

Cloud Modernization with C++: Migrating Legacy Applications to the Cloud Cloud Modernization with C++: Migrating Legacy Applications to the Cloud Jun 01, 2024 am 09:21 AM

The best way to move legacy C++ applications to the cloud: Re-platform: Move the application code to a cloud-native platform (such as Kubernetes) and leverage cloud services. Cloudization: Deploy applications on cloud platforms and utilize cloud services without code refactoring.

How to handle database connection errors in PHP How to handle database connection errors in PHP Jun 05, 2024 pm 02:16 PM

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

How to transfer WeChat chat history to another mobile phone How to transfer WeChat chat history to another mobile phone May 08, 2024 am 11:20 AM

1. On the old device, click "Me" → "Settings" → "Chat" → "Chat History Migration and Backup" → "Migrate". 2. Select the target platform device to be migrated, select the chat records to be migrated, and click "Start". 3. Log in with the same WeChat account on the new device and scan the QR code to start chat record migration.

How to connect to remote database using Golang? How to connect to remote database using Golang? Jun 01, 2024 pm 08:31 PM

Through the Go standard library database/sql package, you can connect to remote databases such as MySQL, PostgreSQL or SQLite: create a connection string containing database connection information. Use the sql.Open() function to open a database connection. Perform database operations such as SQL queries and insert operations. Use defer to close the database connection to release resources.

How to use database callback functions in Golang? How to use database callback functions in Golang? Jun 03, 2024 pm 02:20 PM

Using the database callback function in Golang can achieve: executing custom code after the specified database operation is completed. Add custom behavior through separate functions without writing additional code. Callback functions are available for insert, update, delete, and query operations. You must use the sql.Exec, sql.QueryRow, or sql.Query function to use the callback function.

How to save JSON data to database in Golang? How to save JSON data to database in Golang? Jun 06, 2024 am 11:24 AM

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

See all articles