Home > front end >  Entity Framework scaffold and migration not working
Entity Framework scaffold and migration not working

Time:10-24

I'm using a project with 1 code-first DbContext and 1 database-first DbContext in an asp.net webapi project. Running the following commands to update the db/context results in the following errors:


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 migrations add test -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)

Here is my code

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

I'm literally doing what the exceptions want me to do? Can anybody pls tell me how to fix this?
The application itself runs fine and uses the appsettings/user-secrets with the connectionstrings correctly.
I'm using dotnet 5.0.402 and ef 5.0.11

CodePudding user response:

I would guess that your configuration (appsettings.json/usersecrets) is malformed, should be something like this:

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

Also try removing empty constructor from the context (might cause to be used instead of the one with DbContextOptions)

CodePudding user response:

Changing my Program.cs to

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

fixed the issue

  • Related