【发布时间】: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