Home > Enterprise >  Unable to add a migration for second Db Context in Razor Pages project
Unable to add a migration for second Db Context in Razor Pages project

Time:01-04

The command to add Migration and Error that occurs

I have added the Connection string in the AppSetting.json file And Registered the Context in Program.cs. I am Unable to use migration on second dbContext first migration was done fine.

Appsetting.json File:

  "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 File:

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.")));

CodePudding user response:

Just as the error indicates,it couldn't create an instance of RazorEmployeeContext because you didn't regist them propely in the DI container

Try regist them seperatly :

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.")));

The constructor of each dbcontext

public RazorlistContext(DbContextOptions<RazorlistContext> options)
        : base(options)
    {
    }
public RazorEmployeeContext(DbContextOptions<RazorEmployeeContext> options)
            : base(options)
        {
        }
  • Related