Can not run 'dotnet ef dbcontext scaffold' with user-secrets
It's working with ef core 2.2.
Steps to reproduce
Create secret for project:
dotnet user-secrets init --project DBModel
dotnet user-secrets set ConnectionStrings.Key1 "Host=localhost;Port=5432;Username=postgres;Password=*****;Database=Test;" --project DBModel
Run 'scaffold' to create models:
dotnet ef dbcontext scaffold Name=ConnectionStrings.Key1 Npgsql.EntityFrameworkCore.PostgreSQL -o Models --project DBModel -f --no-build
System.InvalidOperationException: A named connection string was used, but the name 'ConnectionStrings.Key1 ' 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, Boolean useDataAnnotations, Boolean overwriteFiles, Boolean useDatabaseNames)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScaffoldContextImpl(String provider, String connectionString, String outputDir, String outputDbContextDir, String dbContextClassName, IEnumerable`1 schemaFilters, IEnumerable`1 tableFilters, Boolean useDataAnnotations, Boolean overwriteFiles, Boolean useDatabaseNames)
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)
A named connection string was used, but the name 'ConnectionStrings.SolutionBuilder' 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.
Further technical details
EF Core version: 3.1.6 Database provider: Npgsql.EntityFrameworkCore.PostgreSQL Target framework: 3.1 Operating system: Win 10 x64 IDE: Visual Studio 2019 v16.6.5
@robinNode I have not been able to reproduce this. I see you're using the no-build flag. Are you sure the project was built after initializing user-secrets?
@robinNode I have not been able to reproduce this. I see you're using the
no-buildflag. Are you sure the project was built after initializing user-secrets?
After I upgrade to ef core 3.1.6 then it does not work. I have attached the project references. please help to check it whether i forgot to add any required dlls.
PM> dotnet user-secrets init --project Host\Host
The MSBuild project '*******\Host.csproj' has already been initialized with a UserSecretsId.
PM> dotnet user-secrets set ConnectionStrings.Test"Host=localhost;Port=5432;Username=postgres;Password=;Database=Test;" --project Host\Host
Successfully saved ConnectionStrings.Test= Host=localhost;Port=5432;Username=postgres;Password=;Database=Test; to the secret store.
PM> Scaffold-DbContext Name=ConnectionStrings.Test npgsql.EntityFrameworkCore.PostgreSQL -OutputDir Models -f
Build started...
Build succeeded.
System.InvalidOperationException: A named connection string was used, but the name 'ConnectionStrings.Test' 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, IEnumerable1 schemas, IEnumerable1 tables, Boolean useDataAnnotations, Boolean overwriteFiles, Boolean useDatabaseNames)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScaffoldContextImpl(String provider, String connectionString, String outputDir, String outputDbContextDir, String dbContextClassName, IEnumerable1 schemaFilters, IEnumerable1 tableFilters, Boolean useDataAnnotations, Boolean overwriteFiles, Boolean useDatabaseNames)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScaffoldContext.<>c__DisplayClass0_0.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.

@robinNode I don't see anything wrong in anything you posted.
@robinNode Please attach a small project that demonstrates this issue so that we can fully investigate.
I'm also seeing this issue with dotnet-ef 3.1.2 to 3.1.7:
#!/bin/bash
CONNECTION_STRING="Server=localhost,1433;Database=MyDb;User=sa;Password=Welcome1;"
PWD=$(pwd)
dotnet new console --name App.Domain --output ${PWD}/__ef
cd ${PWD}/__ef
dotnet user-secrets init
dotnet user-secrets set ConnectionStrings.MyConnection "${CONNECTION_STRING}"
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet ef dbcontext scaffold Name=MyConnection Microsoft.EntityFrameworkCore.SqlServer --context DataContext --context-dir ./ --output-dir Entities --schema dbo
A named connection string was used, but the name 'MyConnection' 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.
@peterprice I would not expect this to work since a console application does not configure a service provider or use IConfiguration unless you add code to specifically do this. Typically this pattern only works by default for ASP.NET Core projects.
@ajcvickers Thanks Arthur - I didn't put 2 and 2 together, but since you point it out - it makes sense.
I've confirmed that this works for me:
#!/bin/bash
CONNECTION_STRING="Server=localhost,1433;Database=MyDb;User=sa;Password=Welcome1;"
PWD=$(pwd)
dotnet new webapp --name App.Domain --output ${PWD}/__ef
cd ${PWD}/__ef
dotnet user-secrets init
dotnet user-secrets set ConnectionStrings.MyConnection "${CONNECTION_STRING}"
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet ef dbcontext scaffold Name=ConnectionStrings.MyConnection Microsoft.EntityFrameworkCore.SqlServer --context DataContext --context-dir ./ --output-dir Entities --schema dbo
Thank you!
EF Team Triage: Closing this issue as the requested additional details have not been provided and we have been unable to reproduce it.
BTW this is a canned response and may have info or details that do not directly apply to this particular issue. While we'd like to spend the time to uniquely address every incoming issue, we get a lot traffic on the EF projects and that is not practical. To ensure we maximize the time we have to work on fixing bugs, implementing new features, etc. we use canned responses for common triage decisions.
Hello: I know this is almost a full year after this issue was closed, but I just ran into this issue while trying to create a Giraffe web app + efcore. I took a step back and created a few barebones ASP.NET projects to try and figure out what was failing.
tl;dr: looks like dotnet ef dbcontext scaffold ... specifically looks for a static method named CreateHostBuilder(string[]) in Program (as a class or module).
Running that command line with verbose enabled returned this:
<...snip...>
Finding design-time services for provider 'microsoft.entityframeworkcore.sqlserver'...
Using design-time services from provider 'microsoft.entityframeworkcore.sqlserver'.
Finding design-time services referenced by assembly 'giraffe-efcore-test.App'...
Finding design-time services referenced by assembly 'giraffe-efcore-test.App'...
Using design-time services from assembly 'EntityFrameworkCore.FSharp'.
Finding IDesignTimeServices implementations in assembly 'giraffe-efcore-test.App'...
No design-time services were found.
Finding application service provider in assembly 'giraffe-efcore-test.App'...
Finding Microsoft.Extensions.Hosting service provider...
No static method 'CreateHostBuilder(string[])' was found on class 'Program'.
No application service provider was found.
System.InvalidOperationException: A named connection string was used, but the name 'ConnectionStrings:MothershipDB' 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 useDataAnnotations, 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 useDataAnnotations, 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)
A named connection string was used, but the name 'ConnectionStrings:MothershipDB' 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.
Note that this seems to affect both user secrets and appsettings.json—scaffold won't read the connection string from either place if it can't find the hardcoded method name it's looking for.
I created two new projects as a test using the dotnet new CLI: one barebones web project and one mvc project (both as F# projects, but that may not matter).
- The
mvcproject has the correct method name in Program.fs from its template, and I could scaffold successfully using user secrets. - The
webproject creates a method starting with a lowercase 'c' (createHostBuilder(string[])) in Program.fs, and it will report the error above when scaffolding using user secrets. Upcasing the method name toCreateHostBuilderallows the scaffold to succeed.
For reference, I'm using net5.0, SDK 5.0.302, host version 5.0.8, with dotnet-ef version 5.0.8. All on Win10Pro (latest feature release).
Sorry to necrobump this issue, but I hope this information helps. Please let me know if you need any further info, or if you would like me to open a new issue for this.
UPDATE: slight correction... looks like the C# version of web capitalizes its method name 'correctly' so that it can be found when scaffolding... so the F# version of web is the project type revealing the issue.
@jparnzen The discovery of CreateHostBuilder is managed by the ASP.NET Core team. Please file an issue at https://github.com/dotnet/aspnetcore to follow up on issues with this pattern and F#.
For the newcomers who want
- to use User Secret
- to use separated console application projects for doing migration and or scaffolding
- to separate entity model from context, each with its own class library project
please kindly see my repository here: https://github.com/pstricks-fans/Separated-Projects.
I successfully did it (after spending a lot of time doing combinatorial yet educated trial and error). Hopefully it is useful for you guys!
The page doesn't exist, can you repost it?
I had to jump through many hoops to solve this one, as I wanted to use a connection string already available in the main project's appsettings:
- The EF resolver is looking specifically for the entry point class (https://github.com/dotnet/runtime/blob/main/src/libraries/Microsoft.Extensions.HostFactoryResolver/src/HostFactoryResolver.cs#L97) so your current project must be an executable,
- The working directory being the one from where you run the
dotnet efcommand it won't find your appsettings files if they are not physically there (e.g. if they are linked from your main project), so you must load the configuration yourself.
Here is the final code:
public class Program
{
/// <summary>
/// Phony, so that the EF resolver can find our Program.CreateHostBuilder method.
/// </summary>
public static void Main()
{
}
public static IHostBuilder CreateHostBuilder(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile("appsettings.development.json")
.Build();
return Host.CreateDefaultBuilder(args).ConfigureAppConfiguration(builder => builder.AddConfiguration(configuration));
}
}
Finally I can do:
dotnet ef dbcontext scaffold "Name=ConnectionStrings:MyDatabase" Microsoft.EntityFrameworkCore.SqlServer ...