【问题标题】:Unable to create an object of type 'ApplicationDbContex' Blazor ASP.NET Core 6.0无法创建类型为“ApplicationDbContex”的对象 Blazor ASP.NET Core 6.0
【发布时间】:2021-11-10 21:03:31
【问题描述】:

我正在使用 ASP.NET Core 6 托管的 Blazor ASP.NET Core Web 中创建一个 Web 应用程序,当我迁移数据库时出现此错误:

无法创建“ApplicationDbContext”类型的对象。有关设计时支持的不同模式,请参阅https://go.microsoft.com/fwlink/?linkid=851728

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

程序.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 类,因为显然在 ASP.NET Core 6 中不需要它

【问题讨论】:

    标签: entity-framework asp.net-core blazor blazor-webassembly asp.net-blazor


    【解决方案1】:
    1. 在您的 DbContext (ApplicationDbContext.cs) 上添加无参数构造函数

      公共 ApplicationDbContext () { }

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

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        你应该替换

        serviceProvider.GetRequiredService<DbContextOptions<ApplicationDbContext>>()
        

        serviceProvider.GetRequiredService<ApplicationDbContext>()
        

        SeedData 类中:

        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();
                    }
                }
            }
        }
        

        【讨论】:

        • 错误仍然存​​在,您认为我必须更改 ApplicationDbContext 中的某些内容吗?
        猜你喜欢
        • 2021-03-07
        • 2022-12-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-22
        • 1970-01-01
        • 2021-03-20
        • 2020-11-09
        相关资源
        最近更新 更多