无法在 Razor Pages 项目中添加第二个数据库上下文的迁移

问题描述 投票:0回答:2

The command to add Migration and Error that occurs

我已在 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.")));
c# asp.net-core razor-pages
2个回答
0
投票

正如错误所示,它无法创建 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)
        {
        }

0
投票

图片内容为:

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创建”

© www.soinside.com 2019 - 2024. All rights reserved.