InvalidOperationException:没有为此DbContext配置数据库提供程序

时间:2017-04-27 11:40:40

标签: c# asp.net-core 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:Always 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произошлаошибка:   ошибказапускапроцессаSQLServer。 )

     

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

1 个答案:

答案 0 :(得分:2)

如果没有参数化构造函数或覆盖OnConfiguring,则无法实例化DbContext。

您有两种选择:

  1. DbContextOptions<ApplicationDbContext>通过DI传递给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);
        }
    }
    
  3. 更新

    在回复评论时,您需要添加

    <ItemGroup>
      <Content Update="appsettings.json">
        <CopyToOutputDirectory>Always</CopyToOutputDirectory>
      </Content>
    </ItemGroup>
    

    以便将appsettings.json复制到输出目录。或者只需单击appsettings.json文件并将属性窗口中的属性更改为“Build Action:Content”和“CopyToOutputDirectory:Always Always”