简体   繁体   中英

Generating CRUD pages in ASP.NET 6 Razor Pages ends with an error "Unable to resolve service for type DbContextOptions"

I want to generate CRUD pages for my db models, but I get an error.

What I've done:

  1. Created a default ASP.NET Core Web App (Razor Pages) with Individual Account (Identity)
  2. Added and configured InMemory package as a DB provider
  3. Added a 'Student' model + attached a proper DbSet<> to the context
  4. Generated pages for the model (Add Razor Page -> Razor Page using EF (CRUD) -> Model: Student, Data context class: ApplicationDbContext)
  5. Works great

but as soon as I split my solution into 3 projects: Test.App, Test.Common, Test.Infrastructure it doesn't work anymore, outputting the error:

文本

Any ideas why that is happening? When my context class is in the main project it suddenly works again.

The code ( https://github.com/RawMajkel/Test ):

Program.cs

using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Tests.App.Infrastructure.Data;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseInMemoryDatabase(databaseName: "testDatabase"));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddRazorPages();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseMigrationsEndPoint();
}
else
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapRazorPages();

app.Run();

Student.cs

using System.ComponentModel.DataAnnotations;

namespace Tests.Common;

public class Student
{
    [Key]
    public string Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime DateOfBirth { get; set; }
    public int Age { get; set; }
}

ApplicationDbContext.cs

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Tests.Common;

namespace Tests.App.Infrastructure.Data;

public class ApplicationDbContext : IdentityDbContext
{
    public DbSet<Student> Students { get; set; }

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
}

I've also tried changing public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options): base(options)

to

public ApplicationDbContext(DbContextOptions options): base(options)

but it didn't work either.

Have anyone had this problem before? Thanks for your help

Had this issue and to fix it I had to configure the provider in the DbContext class itself (which was not part of the main api entrypoint csproj)

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    // needed for local scafolding of razor views
    if (!optionsBuilder.IsConfigured)
    {
        optionsBuilder.UseNpgsql("mongodb://localhost:27017/ssl=false");
        // or other provider... like optionsBuilder.UseSqlServer("....");
    }
}

There are probably other ways around it but this worked for me. The downside is that you need to install the provider package on the csproj where the DbContext lives.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM