繁体   English   中英

EF Core 2.1 - 没有为此 DbContext 配置数据库提供程序

[英]EF Core 2.1 - No database provider has been configured for this DbContext

我有 ASP.Net Core 2.1 和 EF Core 2.1。 这就是我的 DbContext class 的样子

app.DAL.EF -> 图层

using app.domain;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.Extensions.Configuration;
using System;
using System.IO;

namespace app.EF
{
 public class MyAppContext : DbContext
 {
    public MyAppContext(DbContextOptions<MyAppContext> options)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.ApplyConfiguration(new CustomerConfiguration());
        modelBuilder.HasDefaultSchema("app");
        base.OnModelCreating(modelBuilder);
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);
    }

    public DbSet<Customer> Customers { get; set; }
 }

   public class MyAppContextConfiguration : IDesignTimeDbContextFactory<MyAppContext>
   {
    public MyAppContext CreateDbContext(string[] args)
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
                                            .SetBasePath(Directory.GetCurrentDirectory())
                                            .AddJsonFile("appsettings.json", optional: false, true)
                                            .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT ") ?? "Production" }.json", optional: true)
                                            .Build();

        var optionsBuilder = new DbContextOptionsBuilder<MyAppContext>();
        //optionsBuilder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
        var dbConString = configuration.GetConnectionString("ITMDbConnection");

        optionsBuilder.UseSqlServer(dbConString);

        return new MyAppContext(optionsBuilder.Options);
    }
}

public class CustomerConfiguration : IEntityTypeConfiguration<Customer>
{
    public void Configure(EntityTypeBuilder<Customer> builder)
    {
        builder.HasKey(x => x.Id);
    }
}}

app.DI -> 图层

  public static class Factory
  {
    public static void Initialize(ref IServiceCollection services)
    {
        //services.AddTransient<MyAppContext>();
        services.AddDbContext<MyAppContext>(options =>
        {

        });
        //services.AddTransient<MyAppContextConfiguration>();
        services.AddTransient<ICustomerRepository, CustomerRepository>();
    }
}

app.API -> 图层

 namespace app.api
 {
 public class Startup
 {
     public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        Factory.Initialize(ref services);
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseMvc();
    }
}}

从 Package 管理器控制台运行Add-Migration DbInit时,抛出以下错误

没有为此 DbContext 配置数据库提供程序。 可以通过覆盖 DbContext.OnConfiguring 方法或在应用程序服务提供者上使用 AddDbContext 来配置提供者。 如果使用 AddDbContext,则还要确保您的 DbContext 类型在其构造函数中接受 DbContextOptions object 并将其传递给 DbContext 的基本构造函数。

错误

谢谢!

这就是它所说的 - 没有附加数据库提供程序。

看看你所有的代码。 你在哪里指定数据库提供者? 类似于 UseSqlServer(在 DbContext 的 OnConfiguring 中),具体取决于您要使用的数据库提供程序。

内部配置服务

services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(
        Configuration.GetConnectionString("DefaultConnection")));

在 appsettings.json 中

{
    "ConnectionStrings": {
        "DefaultConnection": "SQL connection string"
    }
}

错误很明显 - 从未配置提供程序和连接。 所有这些代码都可以用这个上下文替换:

public class MyAppContext : DbContext
 {
    public DbSet<Customer> Customers { get; set; }

    public MyAppContext(){}

    public MyAppContext(DbContextOptions<MyAppContext> options)
        :base(options)
    {}

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        //The base method is empty
        modelBuilder.HasDefaultSchema("app");
    }
 }

并在ConfigureServices调用AddDbContext


 public class Startup
 {
     public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<MyAppContext>(options =>
        {
            var dbConString = Configuration.GetConnectionString("ITMDbConnection");
            options.UseSqlServer(dbConString);
        });


        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    ....

}

不过,大多数应用程序都有不止一个 DbContext。 一种选择是向Startup.cs添加另一种方法来注册它们。 对于更复杂的应用程序,例如由不同域/模块/子系统/项目组成的应用程序,更好的主意是创建扩展方法,例如:

public static CustomerDomainExtensions
{
    public static IServicesCollection AddCustomerDomain(this IServicesCollection services,IConfiguration configuration)
    {
        return services.AddCustomerContexts(configuration)
                       .AddRepositories(...)
                       ...;

    }

    public static AddCustomerContexts(this IServicesCollection services,IConfiguration configuration)
    {
        var dbConString = Configuration.GetConnectionString("ITMDbConnection");
        services.AddDbContext<MyAppContext>(options =>
        {
            options.UseSqlServer(dbConString);
        });
        //Add more contexts ...
    }
}

Startup.cs ,这将在ConfigureServices调用。 这就是所有Microsoft.Extensions.*类的工作方式,通过提供用于Startup.cs AddUse扩展方法:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCustomerDomain(Configuration);


    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

编辑

向 DbContext 添加了默认构造函数

我遇到过同样的问题。

您需要将 base(options) 添加到构造函数中。

    public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
    {
    }

这将通过选项参数传递给基本构造函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM