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脚本,这让我们不清楚内部的准确变动。

项目多个数据库怎么办?



posted @ 2023-02-13 23:59  long-livece  阅读(185)  评论(0编辑  收藏  举报