【问题标题】:Unable to create an object of type 'AppDbContext'无法创建“AppDbContext”类型的对象
【发布时间】:2020-11-23 07:05:55
【问题描述】:

为了学习,我正在尝试进行社交登录。

我使用例如https://tecknoworks.com/how-to-integrate-social-login-in-a-web-api-solution/ 按照此示例,我在执行 Add-Migration InitialCreate 时无法创建迁移,但出现错误

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

在搜索时发现使用 add-migration initial -verbose 的建议时出现错误

“访问 Microsoft.Extensions.Hosting 服务时遇到了意外的返回类型。方法 'CreateHostBuilder (string [])' 应返回类型为 'IHostBuilder' 的对象。在没有应用程序服务提供程序的情况下继续。”

public class Program
    {
        public static void Main(string[] args)
        {
            var host = CreateWebHostBuilder(args);

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                var loggerFactory = services.GetRequiredService<ILoggerFactory>();
                var logger = loggerFactory.CreateLogger<Program>();
                try
                {
                    var environment = services.GetRequiredService<IWebHostEnvironment>();

                    if (environment.IsDevelopment())
                    {
                        var context = services.GetRequiredService<Infrastructure.AppDbContext>();
                        MigrateDatabaseToLatestVersion.ExecuteAsync(context).Wait();
                    }
                }
                catch (AppException ex)
                {
                    logger.LogError(ex, "An error occurred creating/updating the DB.");
                }
            }

            host.Run();
        }

        private static IWebHost CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .Build();
    }

代码 AppDbContext

public class AppDbContext : IdentityDbContext<AppUser>
    {
        public AppDbContext(DbContextOptions<AppDbContext> options)
            : base(options)
        {
        }

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

            builder.Entity<AppUser>(entity => { entity.ToTable(name: "tr_Users"); });
            builder.Entity<IdentityRole>(entity => { entity.ToTable(name: "tr_Roles"); });
            builder.Entity<IdentityUserRole<string>>(entity => { entity.ToTable("tr_UserRoles"); });
            builder.Entity<IdentityUserClaim<string>>(entity => { entity.ToTable("tr_UserClaims"); });
            builder.Entity<IdentityUserLogin<string>>(entity => { entity.ToTable("tr_UserLogins"); });
            builder.Entity<IdentityUserToken<string>>(entity => { entity.ToTable("tr_UserTokens"); });
            builder.Entity<IdentityRoleClaim<string>>(entity => { entity.ToTable("tr_RoleClaims"); });

            builder.ApplyConfiguration(new AppUserConfiguration());
        }
    }

配置服务

public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();

            ConfigureSwagger(services);

            services.AddDbContext<AppDbContext>(it =>
            {
                it.UseSqlServer(Configuration["Database:ConnectionString"]);
            },
                 ServiceLifetime.Transient
            );

            CreateIdentityIfNotCreated(services);

            ConfigureAuthenticationSettings(services);

            services.AddScoped<IUserService, UserService>();

            services.AddMvc(options => options.RespectBrowserAcceptHeader = true);
        }

在数据库表 [__EFMigrationsHistory] ​​中创建

【问题讨论】:

  • 您能在您的Start up 中分享ConfigureServices 方法吗?
  • @Yinqiu 添加了ConfigureServices

标签: c# asp.net-core asp.net-web-api


【解决方案1】:

您需要更改 IWebHost CreateWebHostBuilder 方法以返回 IHostBuilder(以及相应的 Main),在您的情况下,它看起来像这样:

public static IHostBuilder CreateWebHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

public static void Main(string[] args)
{
    var host = CreateWebHostBuilder(args).Build();
    .....
    host.Run();
}

我还更改了CreateWebHostBuilder 以使用Host 而不是WebHost,如"Migrate from ASP.NET Core 2.2 to 3.0" docs 中所写。

【讨论】:

  • @Евгений 很乐意提供帮助!
猜你喜欢
  • 1970-01-01
  • 2020-06-30
  • 1970-01-01
  • 1970-01-01
  • 2020-11-09
  • 2021-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多