[英]InvalidOperationException: No database provider has been configured for this DbContext.
[英]InvalidOperationException: No database provider has been configured for this DbContext
context = new ApplicationDbContext();
context.Clients.Add(item);
InvalidOperationException:沒有為此DbContext配置數據庫提供程序。 可以通過重寫DbContext.OnConfiguring方法或在應用程序服務提供程序上使用AddDbContext來配置提供程序。 如果使用AddDbContext,則還應確保DbContext類型在其構造函數中接受DbContextOptions對象,並將其傳遞給DbContext的基本構造函數。
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public ApplicationDbContext()
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
public DbSet<Client> Clients { get; set; }
啟動
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
// For more details on using the user secret store see https://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets<Startup>();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseIdentity();
// Add external authentication middleware below. To configure them please see https://go.microsoft.com/fwlink/?LinkID=532715
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
更新
我加了
// Startup.ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
//////my=>
services.AddDbContext<DbContext>(config =>
{
config.UseSqlServer(Configuration.GetConnectionString("Default"));
});
並在您的appsettings.json中進行配置
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplicationCore-42a4ac05-477c-4ea7-b286-87423170b48a;Trusted_Connection=True;MultipleActiveResultSets=true",
"Default": "Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplicationCore-42a4ac05-477c-4ea7-b286-87423170b48a;"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
}
}
我單擊了appsettings.json文件,並將屬性窗口中的屬性更改為“ Build Action:Content”和“ CopyToOutputDirectory:Copy Always”
<ItemGroup>
<Content Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
錯誤未解決
新錯誤:
var result = await _userManager.CreateAsync(user, model.Password);
處理請求時發生未處理的異常。 SqlException:建立與SQL Server的連接時發生與網絡相關或特定於實例的錯誤。 服務器未找到或無法訪問。 驗證實例名稱正確,並且已將SQL Server配置為允許遠程連接。 (提供程序:SQL網絡接口,錯誤:50-發生本地數據庫運行時錯誤。ВовремязапускаэкземпляраLocalDB版本:SQL Server。)
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity身份,SqlConnectionString connectionOptions,對象providerInfo,bool redirectedUserInstance,SqlConnectionString userConnectionOptions,SessionData reconnectSessionData,bool applyTransientFaultHandling)
沒有參數化構造函數或對OnConfiguring
的覆蓋,您無法實例化OnConfiguring
。
您有兩種選擇:
通過DI將DbContextOptions<ApplicationDbContext>
傳遞給您的ApplicationDbContext
。 這是通過在startup.cs中配置ApplicationDbContext
並解決它(不使用new
關鍵字!!!)來完成的。
// Startup.ConfigureServices services.AddDbContext<DbContext>(config => { config.UseSqlServer(Configuration.GetConnectionString("Default")); });
並在您的appsettings.json中進行配置
{ "ConnectionStrings": { "Default": "YourSQLConnectionStringHere" } }
不建議使用,因為它需要對連接字符串進行硬編碼,因此方法是在DbContext中配置它
public class ApplicationDbContext { public ApplicationDbContext(DbContextOptions options) : base(options) { } // The call of the base constructor via ": base()" is still required public ApplicationDbContext(DbContextOptions options) : base() { } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(Configuration.GetConnectionString("connectionStringHere")); base.OnConfiguring(optionsBuilder); } }
為了回應評論,您需要添加
<ItemGroup>
<Content Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
為了將appsettings.json復制到輸出目錄。 或者,只需單擊appsettings.json文件,然后將屬性窗口中的屬性更改為“ Build Action:Content”和“ CopyToOutputDirectory:Copy Always”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.