我有 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 的基本构造函数。
谢谢!