我已在 AppSetting.json 文件中添加了连接字符串,并在 Program.cs 中注册了上下文。 我无法在第二个 dbContext 上使用迁移,第一次迁移完成得很好。
Appsetting.json 文件:
"AllowedHosts": "*",
"ConnectionStrings": {
"RazorlistContext": "Server=(localdb)\\mssqllocaldb;Database=Razorlist.Data;Trusted_Connection=True;MultipleActiveResultSets=true",
"RazorEmployeeContext": "Server=(localdb)\\mssqllocaldb;Database=Razorlist.Data;Trusted_Connection=True;MultipleActiveResultSets=true"
}
Program.cs 文件:
builder.Services.AddDbContext<RazorlistContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("RazorlistContext") ?? throw new InvalidOperationException("Connection string 'RazorlistContext' not found.")));
builder.Services.AddDbContext<RazorlistContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("RazorEmployeeContext") ?? throw new InvalidOperationException("Connection string 'RazorEmployeeContext' not found.")));
正如错误所示,它无法创建 RazorEmployeeContext 的实例,因为您没有在 DI 容器中正确注册它们
尝试分别注册它们:
builder.Services.AddDbContext<RazorlistContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("RazorlistContext") ?? throw new InvalidOperationException("Connection string 'RazorlistContext' not found.")));
builder.Services.AddDbContext<RazorEmployeeContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("RazorEmployeeContext") ?? throw new InvalidOperationException("Connection string 'RazorEmployeeContext' not found.")));
各个dbcontext的构造函数
public RazorlistContext(DbContextOptions<RazorlistContext> options)
: base(options)
{
}
public RazorEmployeeContext(DbContextOptions<RazorEmployeeContext> options)
: base(options)
{
}
图片内容为:
PM> Add-Migration init -Context RazorEmployeeContext
Build started...
Build succeeded.
Unable to create an object of type 'RazorEmployeeContext'. For different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
PM>
这里是链接:https://go.microsoft.com/fwlink/?linkid=851728,它映射到“学习/.NET/Entity Framework/Entity Framework Core/设计时DbContext创建”