Razor Pages项目中无法为第二个Db Context添加迁移
多DbContext迁移失败的解决方案
问题原因
你在Program.cs里两次注册的都是RazorlistContext,根本没把第二个目标DbContext(比如RazorEmployeeContext)正确注册到服务容器中,EF Core找不到这个上下文,自然没法为它执行迁移操作。
修正代码
先确认你已经定义了第二个DbContext类(比如RazorEmployeeContext),然后修改Program.cs的服务注册代码:
builder.Services.AddDbContext<RazorlistContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("RazorlistContext") ?? throw new InvalidOperationException("Connection string 'RazorlistContext' not found."))); // 替换为你实际的第二个DbContext类名 builder.Services.AddDbContext<RazorEmployeeContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("RazorEmployeeContext") ?? throw new InvalidOperationException("Connection string 'RazorEmployeeContext' not found.")));
执行第二个DbContext的迁移
修正注册后,用下面的命令为第二个上下文创建并应用迁移:
- 创建迁移(替换
InitialCreate为你的迁移名称,RazorEmployeeContext为实际上下文类名):
dotnet ef migrations add InitialCreate -c RazorEmployeeContext -o Migrations/RazorEmployeeMigrations
- 更新数据库:
dotnet ef database update -c RazorEmployeeContext
注意事项
- 两个DbContext如果指向同一个数据库(你的配置里是这样),要注意迁移的执行顺序,避免表结构冲突。
- 确保每个DbContext类都正确继承自
DbContext,并包含对应的实体集合DbSet<T>。
内容的提问来源于stack exchange,提问作者Babar Hussain
相关产品推荐
相关产品推荐

