无法创建 'ApplicationDbContex' Blazor ASP.NET Core 6.0 类型的对象

Unable to create an object of type 'ApplicationDbContex' Blazor ASP.NET Core 6.0

我在 Blazor ASP.NET Core web 中创建一个 Web 应用程序 ASP.NET Core 6,当我迁移数据库时,我遇到了这个错误:

Unable to create an object of type 'ApplicationDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

我需要一个解决方案 - 这是我的代码:

Program.cs

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();

builder.Services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(builder.Configuration.GetConnectionString("Prueba")));

builder.Services.AddDefaultIdentity<ApplicationUser>()
                   .AddRoles<IdentityRole>()
                   .AddEntityFrameworkStores<ApplicationDbContext>();

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                   .AddJwtBearer(options =>
                   {
                       options.TokenValidationParameters = new TokenValidationParameters
                       {
                           ValidateIssuer = true,
                           ValidateAudience = true,
                           ValidateLifetime = true,
                           ValidateIssuerSigningKey = true,
                           ValidIssuer = builder.Configuration["JwtIssuer"],
                           ValidAudience = builder.Configuration["JwtAudience"],
                           IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["JwtSecurityKey"]))
                       };
                   });

builder.Services.AddAuthorization(config =>
 {
    config.AddPolicy(Policies.IsAdmin, Policies.IsAdminPolicy());
    config.AddPolicy(Policies.IsUser, Policies.IsUserPolicy());
 });
builder.Services.AddSignalR();

builder.Services.AddMvc().AddNewtonsoftJson(options =>
           options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
builder.Services.AddControllersWithViews();
//builder.Services.AddRazorPages();
builder.Services.AddResponseCompression(option =>
{
    option.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat

    (new[] { "application/octet-stream"
    });
});

var app = builder.Build();

using (var scope = app.Services.CreateScope())
{
    var services = scope.ServiceProvider;

    SeedData.Initialize(services);
}

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
    app.UseWebAssemblyDebugging();
}
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.UseBlazorFrameworkFiles();
app.UseStaticFiles();

app.UseRouting();

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


app.MapRazorPages();
app.MapControllers();
app.MapFallbackToFile("index.html");
app.UseEndpoints(endpoints =>
{
    endpoints.MapHub<UsuariosHub>("/UsuariosHub");
});
app.Run();

ApplicationDbContext.cs

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using ProyectoBP.Shared.Models;

namespace ProyectoBP.Server.Data;

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

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
    }

    public DbSet<Movie> Movies { get; set; }
}

SeedData.cs

using Microsoft.EntityFrameworkCore;
using ProyectoBP.Server.Data;

namespace ProyectoBP.Shared.Models
{
    public static class SeedData
    {
        public static void Initialize(IServiceProvider serviceProvider)
        {
            using (var context = new ApplicationDbContext(
                serviceProvider.GetRequiredService<
                    DbContextOptions<ApplicationDbContext>>()))
            {
                context.SaveChanges();

                if (context == null || context.Movies == null)
                {
                    throw new ArgumentNullException("Null ApplicationDbContext");
                }

                // Look for any movies.
                if (context.Movies.Any())
                {
                    return;   // DB has been seeded
                }
                  
                context.SaveChanges();
            }
        }
    }
}

appsettings.json

{
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=ISMAEL-PC;Initial Catalog=BP;Integrated Security=False;uid=JoseD;password=Laugama2021.",
    "Prueba": "Data Source=ISMAEL-PC;Initial Catalog=BP;Integrated Security=true"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }
}

我没有 StartUp Class 因为显然 ASP.NET Core 6 不需要它

你应该更换

serviceProvider.GetRequiredService<DbContextOptions<ApplicationDbContext>>()

serviceProvider.GetRequiredService<ApplicationDbContext>()

SeedData class :

using Microsoft.EntityFrameworkCore;
using ProyectoBP.Server.Data;
namespace ProyectoBP.Shared.Models
{
    public static class SeedData
    {
        public static void Initialize(IServiceProvider serviceProvider)
        {
            using (var context = serviceProvider.GetRequiredService<ApplicationDbContext>())
            {
                context.SaveChanges();

                if (context == null || context.Movies == null)
                {
                    throw new ArgumentNullException("Null ApplicationDbContext");
                }

                // Look for any movies.
                if (context.Movies.Any())
                {
                    return;   // DB has been seeded
                }
                  
                context.SaveChanges();
            }
        }
    }
}
  1. 在 DbContext 上添加无参数构造函数 (ApplicationDbContext.cs)

    publicApplicationDbContext() { }

  2. 确保将默认启动项目设置为 WebApplication

或在更新命令末尾添加 -s {Satrtup 项目名称}

  1. 将 Microsoft.EntityFrameworkCore.Design 包添加到 WebApplication 项目

我通过检查 include prerelease 选项解决了我的问题,因为我在预发布版本中使用 ASP.NET Core 6,但我试图迁移到当前的稳定版本。所以我希望这可以帮助你。

临时 re-register 从 AddSingleton 和 AddScoped 到 AddTransient 的所有服务。它对我有用。