InvalidOperationException:尚未為此DbContext配置任何數據庫提供程序

asp.net-core c# entity-framework-core

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 - 發生本地數據庫運行時錯誤.Ð'оÐÑÑÐÐÐÐÐÐÐÐÐÐÐÐÐÐÐÐÑÐÑа°°Ðto to to to to to to to to to to to to to to to to to to to in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in in ÐÐÐÐÐÐÐÐÐÐÐÐÐÐÐÐÐÐÐÐÐÐÐÐÐÐÐÐÐÐÐÐÐÐÐÑÑÑÑ°°°°°°°°°°°°°°°°°°

System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity,SqlConnectionString connectionOptions,object providerInfo,bool redirectedUserInstance,SqlConnectionString userConnectionOptions,SessionData reconnectSessionData,bool applyTransientFaultHandling)

一般承認的答案

如果沒有參數化構造函數或對OnConfiguring的覆蓋,則無法實例化OnConfiguring

你有兩個選擇:

  1. 通過DI將DbContextOptions<ApplicationDbContext>傳遞給ApplicationDbContext 。這是最簡單的方法,通過在startup.cs中配置ApplicationDbContext並解析它(不使用new關鍵字!!!)

    // Startup.ConfigureServices
    services.AddDbContext<DbContext>(config => 
    {
        config.UseSqlServer(Configuration.GetConnectionString("Default"));
    });
    

    並在appsettings.json中配置它

    {
        "ConnectionStrings": {
            "Default": "YourSQLConnectionStringHere"
        }
    }
    
  2. 不太推薦,因為它需要對連接字符串進行硬編碼,方法是在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”



Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow