Migration使用
Migration
分层项目迁移命令
1.单数据库
# 1、切换到DbContext项目:Infrastructure
# 2、用于Migration需要两个包:
启动项添加包 Microsoft.EntityFrameworkCore.Design
基础设施项可能需要包 Microsoft.EntityFrameworkCore.Tools
(原因https://blog.csdn.net/sundna/article/details/100544285)
# 3、执行Add-Migration Init -s EFCoreDatabase
(执行Add-Migration Init -s EFCoreDatabase与有没有下面的构造函数毫无关系,构造函数只是为了在别的地方需要new的时候用)
# 4、执行Update-database
2.多数据库
# 1、切换到DbContext项目:Infrastructure
# 2、用于Migration需要两个包:
启动项添加包 Microsoft.EntityFrameworkCore.Design
基础设施项可能需要包 Microsoft.EntityFrameworkCore.Tools
(原因https://blog.csdn.net/sundna/article/details/100544285)
# 3、执行Add-Migration Init -Context MyDbContext2 -s EFCoreDatabase
(执行Add-Migration Init -s EFCoreDatabase与有没有下面的构造函数毫无关系,构造函数只是为了在别的地方需要new的时候用)
# 4、执行Update-database -Context MyDbContext2
使用数据库上下文
1.单数据库
不使用依赖注入
//无参构造函数是默认的
public MyDbContext()
{
}
protected override void OnConfiguring(DbContextOptionsBuilder builder)
{ builder.UseSqlServer("Server=.;Database=tx2;Trusted_Connection=True;Encrypt=True;TrustServerCertificate=True;");
base.OnConfiguring(builder);
}
using (MyDbContext db = new MyDbContext())
{
}
使用依赖注入
protected override void OnConfiguring(DbContextOptionsBuilder builder)
{ builder.UseSqlServer("Server=.;Database=tx2;Trusted_Connection=True;Encrypt=True;TrustServerCertificate=True;");
base.OnConfiguring(builder);
}
builder.Services.AddDbContext<MyDbContext2>();
public MyDbContext2(DbContextOptions options) : base(options)
{
}
builder.Services.AddDbContext<MyDbContext2>(opt => { opt.UseSqlServer("Server=.;Database=tx2;Trusted_Connection=True;Encrypt=True;TrustServerCertificate=True;");
});
//如果不写MyDbContext2(DbContextOptions options) : base(options) 则会报错原因是:
当您尝试使用 AddDbContext 方法注册没有接受 DbContextOptions<TContext> 参数的构造函数的 DbContext 类型时,会发生此错误。若要修复此错误,需要向接受 DbContextOptions<TContext> 参数的 DbContext 类型添加一个构造函数
2.多数据库
使用依赖注入
public MyDbContext2(DbContextOptions<MyDbContext2> options) : base(options)
{
}
builder.Services.AddDbContext<MyDbContext2>(opt => { opt.UseSqlServer("Server=.;Database=tx2;Trusted_Connection=True;Encrypt=True;TrustServerCertificate=True;");
});
_EFMigratoinsHistory表
每次Update-database的时候都会将最后一个迁移文件的名字20230213125523_Ad及它的Designer文件中[Migration("20230213125523_Ad")](前面两个必需相同)去和__EFMigratoinsHistory表的最后一行的MigrationId值对比,如果值一样就efcore就认为没变化不执行迁移,如果名称不一样则执行迁移。所以最好不要动__EFMigratoinsHistory表的值!
其他参数
# 回滚和删除
https://www.cnblogs.com/shanfeng1000/p/13377957.html
# Script-Migration
正常来说公司不会让开发人员直接操作已经上线了的数据库,因为不小心就会造成非常大破坏,所以需要使用Script-Migration指定生成某个改动的sql脚本,给公司Dbo管理者审核过再到数据库执行sql脚本。而Update-Database操作其实就是EFCore框架先帮我们Script-Migration 生成sql脚本再执行sql脚本,这让我们不清楚内部的准确变动。
项目多个数据库怎么办?
、
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗