0

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

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();
    }
}}

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

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

错误

谢谢!

4

3 回答 3

0

内部配置服务

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

在 appsettings.json

{
    "ConnectionStrings": {
        "DefaultConnection": "SQL connection string"
    }
}
于 2020-03-04T08:47:14.127 回答
0

就像它所说的那样 - 没有附加数据库提供程序。

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

于 2020-03-04T08:43:34.203 回答
0

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

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");
    }
 }

并调用AddDbContextinside ConfigureServices


 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 ...
    }
}

in Startup.cs,这将被称为 inside ConfigureServices。这就是所有Microsoft.Extensions.*类的工作方式,通过提供AddUse扩展方法用于Startup.cs

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


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

编辑

向 DbContext 添加了默认构造函数

于 2020-03-04T09:15:08.720 回答