当我尝试在 ASP.NET Core 项目上进行 EF 迁移时,我遇到此错误。
我执行的命令是:
dotnet ef migrations add "InitialMigration" -o Data/Migrations
这是我得到的错误:
尚未为此 DbContext 配置数据库提供程序。可以通过重写“DbContext.OnConfiguring”方法或在应用程序服务提供程序上使用“AddDbContext”来配置提供程序。如果使用“AddDbContext”,则还要确保您的 DbContext 类型在其构造函数中接受 DbContextOptions 对象,并将其传递给 DbContext 的基本构造函数
这是
Program.cs
代码
internal class Program
{
private static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services
.AddInfrastructureServices(builder.Configuration);
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseAuthorization();
app.MapControllers();
app.Run();
}
}
这是
DbContext
代码:
public class AuctionDbContext : DbContext
{
public AuctionDbContext()
{
}
public AuctionDbContext(DbContextOptions<AuctionDbContext> options) : base(options)
{
}
public DbSet<Auction> Auctions { get; set; }
}
这是
DependencyInjection
课程
public static class DependencyInjection
{
public static IServiceCollection AddInfrastructureServices(this IServiceCollection services, IConfiguration configuration)
{
var connectionString = configuration.GetConnectionString("DefaultConnection");
if (connectionString is null)
{
Console.WriteLine("Connection string 'DefaultConnection' not found.");
}
services.AddDbContext<AuctionDbContext>(option =>
{
option.UseNpgsql(connectionString);
});
return services;
}
}
我尝试了不同的解决方案:
DbContext
类添加无参数构造函数Program.cs
类中通过重写 OnConfiguring 方法并在此处手动添加 ConnectionString 解决了问题
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseNpgsql("YourConectionString");
}
}