.NET6 DbContext未配置数据库提供程序(无需OnConfiguring)
问题描述
执行EF Core迁移时遇到两类错误:
错误1:未添加DbContext空构造函数时
Unable to create an object of type 'ApplicationDbContext'. For the different patterns supported at design time...
对应的DbContext代码:
public class ApplicationDbContext : IdentityDbContext<Pessoas> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options): base(options) { } public DbSet<Pessoas> Pessoas { get; set; } public DbSet<Creditos> Creditos { get; set; } public DbSet<Debitos> Debitos { get; set; } protected override void OnModelCreating(ModelBuilder builder) { builder.Ignore<Notification>(); builder.Entity<Pessoas>().ToTable(nameof(Pessoas)).HasKey(p => p.Id); base.OnModelCreating(builder); } protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) { configurationBuilder.Properties<String>() .HaveMaxLength(100); configurationBuilder.Properties<int>() .HaveMaxLength(4); base.ConfigureConventions(configurationBuilder); } }
错误2:添加空构造函数后
No database provider has been configured for this DbContext. A provider can be configured by overriding the 'DbContext.OnConfiguring' method or by using 'AddDbContext' on the application service provider. If 'AddDbContext' is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.
对应的DbContext代码:
public class ApplicationDbContext: IdentityDbContext<Pessoas> { public ApplicationDbContext() { } public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options): base(options) { } public DbSet<Pessoas> Pessoas { get; set; } public DbSet<Creditos> Creditos { get; set; } public DbSet<Debitos> Debitos { get; set; } protected override void OnModelCreating(ModelBuilder builder) { builder.Ignore<Notification>(); builder.Entity<Pessoas>().ToTable(nameof(Pessoas)).HasKey(p => p.Id); base.OnModelCreating(builder); } protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) { configurationBuilder.Properties<String>() .HaveMaxLength(100); configurationBuilder.Properties<int>() .HaveMaxLength(4); base.ConfigureConventions(configurationBuilder); } }
当前Program.cs配置
var builder = WebApplication.CreateBuilder(args); builder.Services.AddDbContext<ApplicationDbContext>( options => options.UseSqlServer(builder.Configuration["ConnectionString:Connection"]) ); builder.Services.AddIdentity<Pessoas, IdentityRole>(options => { options.Password.RequireNonAlphanumeric = false; options.Password.RequireDigit = false; options.Password.RequireUppercase = false; options.Password.RequireLowercase = false; options.Password.RequiredLength = 3; }).AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); builder.Services.AddScoped<IPessoas, PessoasRepository>(); builder.Services.AddScoped<IPessoasApplication, PessoasService>(); builder.Services.AddControllers(); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run();
目前只有重写DbContext.OnConfiguring方法并显式指定连接字符串才能正常执行迁移,但希望找到无需重写该方法的解决方案——教程中仅通过Program.cs配置即可正常迁移,克隆的示例项目自己执行迁移时出现相同错误,但朋友执行却成功。
解决方案
1. 移除DbContext的空构造函数
EF Core设计时工具会优先尝试使用无参构造函数,导致无法读取Program.cs中配置的DbContextOptions。保留带DbContextOptions<ApplicationDbContext>参数的构造函数即可,无需空构造。
2. 执行迁移时指定启动项目(如果DbContext在类库)
如果你的DbContext类在单独的类库项目中,而Program.cs在Web项目里,执行迁移命令时必须指定启动项目,让EF Core能读取到配置:
使用.NET CLI:
dotnet ef migrations add InitialCreate --project YourDbContextLibraryName --startup-project YourWebProjectName
使用Package Manager Console:
Add-Migration InitialCreate -Project YourDbContextLibraryName -StartupProject YourWebProjectName
3. 验证连接字符串配置
确保appsettings.json中的键名与Program.cs中读取的ConnectionString:Connection完全匹配,示例:
{ "ConnectionString": { "Connection": "Server=.;Database=YourDatabaseName;Trusted_Connection=True;TrustServerCertificate=True;" } }
4. 统一EF Core包版本
检查项目中所有EF Core相关包(Microsoft.EntityFrameworkCore、Microsoft.EntityFrameworkCore.SqlServer、Microsoft.EntityFrameworkCore.Tools)的版本是否一致,且与当前使用的.NET SDK版本兼容。版本不匹配会导致设计时工具无法正确加载配置。
5. 清理项目缓存并重新生成
清理解决方案的bin和obj目录,然后重新生成整个解决方案,再尝试执行迁移命令,避免缓存导致的配置读取异常。
内容的提问来源于stack exchange,提问作者medeirosGabriel

