更新记录
转载请注明出处:
2022年10月23日 发布。
2022年10月22日 从笔记迁移到博客。
EF 迁移介绍
EF 迁移说明
EF Core API builds the EF Core model from the domain (entity) classes and EF Core migrations will create or update the database schema based on the EF Core model
当修改了域模型后,需要通过迁移来更新变化到数据库之中
EF迁移工具支持两种类型的命令:
NuGet Package Manager Console(PMC)
dotnet Command Line Interface (CLI)
注意:EF6只支持PMC、EF Core支持两种
EF 迁移文件夹结构
当使用命令添加迁移后,会在项目的目录下生成一个Migrations文件夹
该文件夹下包含迁移生成的代码
_
.cs:
The main migration file which includes migration operations in the Up() and Down() methods.
The Up() method includes the code for creating DB objects and Down() method includes code for removing DB objects.
_
.Designer.cs:
The migrations metadata file which contains information used by EF Core.
ModelSnapshot.cs:
A snapshot of your current model. This is used to determine what changed when creating the next migration.
向上迁移和向下迁移
使用迁移脚本,可以对当前连接的数据库执行编号更高的迁移,这个操作叫做“向上迁移”(Up),也可以执行把数据库回退到旧的迁移,这个操作叫“向下迁移”(Down)、除非有特殊需要,否则不要删除Migrations文件夹下的代码。
进一步分析Migrations下的代码。分析Up、Down等方法。查看Migration编号。
查看数据库的_EFMigrationsHistory表:记录当前数据库曾经应用过的迁移脚本,按顺序排列。
EF生成的数据库
EF 迁移生成工具会在生成的数据中创建一个名为:__EFMigrationsHistory的表
EF工具安装
如果使用Visual Studio相关的工具链,安装以下包
使用PowerShell Package Manager Console进行安装包
Install-Package Microsoft.EntityFrameworkCore.Design
使用dotnet工具进行安装
dotnet add package Microsoft.EntityFrameworkCore.Design
注意:Design包如果是只使用PMC工具,可以不用安装
注意:使用命令行,先要进入到项目目录下
安装dotnet迁移工具
dotnet tool install --global dotnet-ef
移除dotnet迁移工具
dotnet tool uninstall --global dotnet-ef
卸载EF Core工具
dotnet tool uninstall --global dotnet-ef
安装EF Core工具(指定版本)
dotnet tool install --global dotnet-ef --version 5.0.0
EF Core工具查看版本
dotnet ef --version
强制把数据库删除
dotnet ef database drop --force
EF Core Migrations命令
Migrations命令概述
EF Core工具包含不同的命令用于创建和更新数据库和模型
可以两种不同的命令工具来实现EF的迁移管理:
Package Manager Console
dotnet CLI EF Tools
Migrations命令使用前注意
注意:使用迁移工具前,记得加载Microsoft.EntityFrameworkCore.Design包
注意:使用迁移工具前,保证创建了数据库上下文DbContext并配置数据库连接信息
提示:迁移记录将会被存储在数据库中的__EFMigrationsHistory表中
主要的dotnet CLI EF Core Migrations管理工具命令
Database | 管理数据库,子命令包括drop和update |
---|---|
DbContext | 管理DbContext类型,子命令包括scaffold、list、info |
Migrations | 管理迁移,子命令包括add、list、remove、script |
Migrations(迁移管理命令)
迁移管理说明
注意:在执行迁移命令之前,记得先将路径切换到项目目录下,然后再执行
DotNet EF Core迁移管理工具命令概述
migrations add //添加新迁移
migrations remove //移除旧迁移
migrations list //列出可用的迁移
migrations script //从指定迁移生成SQL代码
添加迁移(使用dotnet命令)(Adding a Migration)
dotnet ef migrations add [migration name]
实例:新建迁移
dotnet ef migrations add Initial
移除迁移(使用dotnet命令)
注意:在移除迁移记录前,要确保数据库没有应用该迁移
dotnet ef migrations remove [migration name]
导出SQL脚本(使用dotnet命令)
dotnet ef migrations script [arguments] [options]
参数:
The starting migration. Defaults to ‘0’ (the initial database)
The ending migration. Defaults to the last migration
Options:
-o|--output <FILE> The file to write the result to.
-i|--idempotent Generate a script that can be used on a database at any migration.
-c|--context <DBCONTEXT> The DbContext to use.
-p|--project <PROJECT> The project to use.
-s|--startup-project <PROJECT> The startup project to use.
--framework <FRAMEWORK> The target framework.
--configuration <CONFIGURATION> The configuration to use.
--runtime <RUNTIME_IDENTIFIER> The runtime to use.
--msbuildprojectextensionspath <PATH> The MSBuild project extensions path. Defaults to "obj".
--no-build Don't build the project. Only use this when the build is up-to-date.
-h|--help Show help information
-v|--verbose Show verbose output.
--no-color Don't colorize output.
--prefix-output Prefix output with level.
实例:导出SQL脚本到文件
dotnet ef migrations script -o D:/test.sql
列出迁移记录
dotnet ef migrations list
支持以下选项:
Options:
–json Show JSON output
-c|–context
The DbContext to use
-p|–project
-s|–startup-project
–framework
The target framework
–configuration
The configuration to use
–runtime <RUNTIME_IDENTIFIER> The runtime to use
–msbuildprojectextensionspath
–no-build Don’t build the project. Only use this
when the build is up-to-date
启用迁移(使用PMC命令)
Enable-Migrations
启用迁移(开启自动迁移)
Enable-Migrations -EnableAutomaticMigrations
添加迁移(使用PMC命令)
添加迁移
add-migration "migration name"
实例:添加迁移
add-migration "Initial Migration"
移除迁移(使用PMC命令)
注意:在移除迁移记录前,要确保数据库没有应用该迁移
remove-migration "migration name
实例:
导出SQL脚本(使用PMC命令)
script-migration
Database(数据库管理)
数据库管理说明
DotNet EF Core数据库管理工具命令汇总:
database drop //删除数据库的内容
database update //更新数据到指定的迁移记录
更新数据库(使用dotnet命令)
说明:将实体(Entity)及其关系更新到数据库
注意:执行该命令后会在数据库中生成一个__EFMigrationsHistory表
dotnet ef database update [arguments] [options]
参数:
The target migration. If ‘0’, all migrations will be reverted. Defaults to the last migration
Options:
-c|–context
The DbContext to use.
-p|–project
-s|–startup-project
–framework
The target framework
–configuration
The configuration to use
–runtime <RUNTIME_IDENTIFIER> The runtime to use
–msbuildprojectextensionspath
–no-build Don’t build the project. Only use this when the build is up-to-date
-h|–help Show help information
-v|–verbose Show verbose output
–no-color Don’t colorize output
–prefix-output Prefix output with level
实例:更新数据库到最新的迁移记录
dotnet ef database update
实例:更新数据库到指定的迁移记录
dotnet ef database update 20200903081609_2020年9月3日161501
删除数据库(使用dotnet命令)
将数据库中已存在的表删除(由Migrations命令生成的表)
dotnet ef database drop
实例:强制删除已有的数据库
dotnet ef database drop --force --context StoreDbContext
更新数据库(使用PMC命令)
update-database
update-database -migration [name-of-your-migration]
实例:更新数据到指定的迁移记录
update-database -targetmigration InitialMigration
删除数据库(使用PMC命令)
Remove-Database
DbContext(上下文对象管理)
DbContext(上下文对象管理)说明
DotNet EF Core上下文对象管理工具命令汇总:
dbContext info //获得dbcontext的信息
dbContext list //列出可用的Dbcontext
dbContext scaffold //从数据库生成DbContext和实体类型的代码
dbContext script //从迁移中生成代码
获得具体上下文对象的信息(使用dotnet命令)
dotnet ef dbcontext info
列出可用的上下文对象(使用dotnet命令)
dotnet ef dbcontext list
从当前的迁移状态生成SQL代码(使用dotnet命令)
dotnet ef dbcontext script
从数据库生成Code-First的模型和上下文对象(使用dotnet命令)
dotnet ef dbcontext scaffold [arguments] [options]
Arguments:
The connection string to the database.
Options:
-d|–data-annotations Use attributes to configure the model (where possible). If omitted, only the fluent API is used.
-c|–context
The name of the DbContext.
–context-dir
-f|–force Overwrite existing files.
-o|–output-dir
–schema <SCHEMA_NAME>… The schemas of tables to generate entity types for.
-t|–table <TABLE_NAME>… The tables to generate entity types for.
–use-database-names Use table and column names directly from the database.
–json Show JSON output.
-p|–project
-s|–startup-project
–framework
The target framework.
–configuration
The configuration to use.
–runtime <RUNTIME_IDENTIFIER> The runtime to use.
–msbuildprojectextensionspath
–no-build Don’t build the project. Only use this when the build is up-to-date.
-h|–help Show help information
-v|–verbose Show verbose output.
–no-color Don’t colorize output.
–prefix-output Prefix output with level.
实例:从数据库生成上下文对象和模型
dotnet ef dbcontext scaffold 'Server=192.168.1.13;Database=Panest;User Id=sa;Password=1;' Microsoft.EntityFrameworkCore.SqlServer
实例:指定上下文对象的目录 和 Model的目录
dotnet ef dbcontext scaffold 'Server=192.168.1.198;Datab
ase=PandaTest;User Id=sa;Password=password;' Microsoft.EntityFrameworkCore.SqlServer --context-dir data --output-dir Models
实例:指定上下文对象的类名
dotnet ef dbcontext scaffold 'Server=192.168.1.18;Datab
ase=PandaTest;User Id=sa;Password=1;' Microsoft.EntityFrameworkCore.SqlServer --context PandaC
实例:指定上下文对象的目录 和 Model的目录
dotnet ef dbcontext scaffold 'Server=127.0.0.1;Database=test;User Id=sa;Password=1sda;' Microsoft.EntityFrameworkCore.SqlServer --context PandaContext --context-dir Data --output-dir Models
从数据库生成Code-First的模型和上下文对象(使用PMC命令)
Scaffold-DbContext [-Connection] [-Provider] [-OutputDir] [-Context] [-Schemas>] [-Tables>] [-DataAnnotations] [-Force] [-Project] [-StartupProject] [
]
实例1:
Scaffold-DbContext "Server(localdb)\mssqllocaldb;Database=MasteringEFCoreDbFirst;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
实例2:
Scaffold-DbContext "Server=.\SQLExpress;Database=SchoolDB;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
获得帮助信息
获得帮助信息(使用dotnet命令)
dotnet ef -h
获得帮助信息(使用PMC命令)
Get-Help entityframework
EF 数据迁移(Migrations)工具
使用迁移指令
在VS中改动实体的结构需要对数据库进行更新
启用数据库迁移
Enable-Migrations
会在项目中创建一个名为Migrations文件夹
并在该文件夹下创建一个Configuration.cs配置类
通过这个配置类,可以实现数据库的初始化工作
添加数据库迁移
Add-Migration <迁移名称>
Add-Migration PandaTest //实例
更新到数据库中
Update-Database
数据模型变更自动管理
除了使用数据迁移指令之外,还可以配置变更自动管理,即使用数据库初始化器
方法:使用Database类的SetInitializer静态方法
在Global.asax文件中,添加对应的代码即可:
注意:需要引入System.Data.Entity命名空间
支持的变更管理策略:
//每次都强制对数据库进行删除再进行新建数据库
Database.SetInitializer(new DropCreateDatabaseAlways<PandaDbContext>());
//如果数据库变更了对数据库进行删除再进行新建数据库
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<PandaDbContext>());
实例代码:
using System;
using System.Data.Entity;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using WebApplication8.Data;
namespace WebApplication8
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
//每次都强制对数据库进行删除再进行新建数据库
Database.SetInitializer(new DropCreateDatabaseAlways<PandaDbContext>());
//如果数据库变更了对数据库进行删除再进行新建数据库
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<PandaDbContext>());
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
自动变更管理与数据迁移对比
自动变更管理会直接删除原有数据库,而数据迁移会保留
自动变更适合开发的早期,数据迁移适合有数据的应用
原文地址:http://www.cnblogs.com/cqpanda/p/16815263.html