Entity Framework 脚手架和迁移不工作

Entity Framework scaffold and migration not working

我在 asp.net webapi 项目中使用一个项目,该项目具有 1 个代码优先 DbContext 和 1 个数据库优先 DbContext。 运行 以下更新 db/context 的命令会导致以下错误:


dotnet ef dbcontext scaffold Name=ConnectionStrings:Cloud Microsoft.EntityFrameworkCore.SqlServer

System.InvalidOperationException: A named connection string was used, but the name 'ConnectionStrings:Cloud' was not found in the application's configuration. Note that named connection strings are only supported when using 'IConfiguration' and a service provider, such as in a typical ASP.NET Core application. See
 https://go.microsoft.com/fwlink/?linkid=850912 for more information.
   at Microsoft.EntityFrameworkCore.Storage.Internal.NamedConnectionStringResolverBase.ResolveConnectionString(String connectionString)
   at Microsoft.EntityFrameworkCore.Scaffolding.Internal.ReverseEngineerScaffolder.ScaffoldModel(String connectionString, DatabaseModelFactoryOptions databaseOptions, ModelReverseEngineerOptions modelOptions, ModelCodeGenerationOptions codeOptions)
   at Microsoft.EntityFrameworkCore.Design.Internal.DatabaseOperations.ScaffoldContext(String provider, String connectionString, String outputDir, String outputContextDir, String dbContextClassName, IEnumerable`1 schemas, IEnumerable`1 tables, String modelNamespace, String contextNamespace, Boolean useDataAnnotati
ons, Boolean overwriteFiles, Boolean useDatabaseNames, Boolean suppressOnConfiguring, Boolean noPluralize)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScaffoldContextImpl(String provider, String connectionString, String outputDir, String outputDbContextDir, String dbContextClassName, IEnumerable`1 schemaFilters, IEnumerable`1 tableFilters, String modelNamespace, String contextNamespace, Boolean useData
Annotations, Boolean overwriteFiles, Boolean useDatabaseNames, Boolean suppressOnConfiguring, Boolean noPluarlize)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScaffoldContext.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)

dotnet ef 迁移添加测试 -c AdminContext

System.InvalidOperationException: 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<TContext> object in its constructor and passes it to the base constructor for DbContext.
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.Initialize(IServiceProvider scopedProvider, IDbContextOptions contextOptions, DbContext context)
   at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
   at Microsoft.EntityFrameworkCore.DbContext.Microsoft.EntityFrameworkCore.Infrastructure.IInfrastructure<System.IServiceProvider>.get_Instance()
   at Microsoft.EntityFrameworkCore.Infrastructure.Internal.InfrastructureExtensions.GetService[TService](IInfrastructure`1 accessor)
   at Microsoft.EntityFrameworkCore.Infrastructure.AccessorExtensions.GetService[TService](IInfrastructure`1 accessor)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType, String namespace)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType, String namespace)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)

这是我的代码

   public static class Program {
       public static void Main(string[] args) {
           Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }).Build().Run();
       }
   }
   public class Startup {
       public Startup(IConfiguration configuration) {
           Configuration = configuration;
       }

       private 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<AdminContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Admin")));
           services.AddDbContext<CloudContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Cloud")));
           services.AddControllers();
       }

       public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
           app.UseHsts();
           app.UseHttpsRedirection();
           app.UseRouting();
           app.UseAuthorization();
           app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
       }
   }
    public class AdminContext : DbContext {
        public AdminContext() { }
        public AdminContext(DbContextOptions<AdminContext> options) : base(options) { }
        
        public DbSet<User> Users { get; set; }
    }

我真的是在做例外要我做的事吗?谁能告诉我如何解决这个问题?
应用程序本身运行良好,并正确使用 appsettings/user-secrets 和连接字符串。
我正在使用 dotnet 5.0.402 和 ef 5.0.11

我猜你的配置 (appsettings.json/usersecrets) 格式不正确,应该是这样的:

{
  "ConnectionStrings": {
    "Admin": "***",
    "Cloud": "***"
  },
  ...
}

也尝试从上下文中删除空构造函数(可能会导致使用而不是带有 DbContextOptions 的构造函数)

正在将我的 Program.cs 更改为

    public static class Program {
        public static void Main(string[] args) => CreateHostBuilder(args).Build().Run();

        // EF Core uses this method at design time to access the DbContext
        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>());
    }

已解决问题