You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Stop adding connection string into code when scaffolding #10432
It generates a ApiDbContext.cs file with the following:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
optionsBuilder.UseSqlServer(@"<connection string>");
}
I have literally just spent 2 hours trying to figure out why my our staging environments were hitting our development databases instead of our production databases. We run this command every time we have any database schema changes (because we do database first instead of code first) and this time I forgot to remove this.
It got lost in a code review because of other changes in that file as well as lots of changes in other areas of the code.
It got lost in the warnings message because the current build has a lot of warnings because of [Obsolete] tags that we cannot remedy immediately.
To me this whole situation is not good, if for no other reason then you are encouraging users to put their sensitive connection strings in source control while at the same time saying "this is a bad practice but we will still shove this in your code every time you run this command". All it takes is one person to miss that message and it's in source control forever (or can be a royal pain to remove if it's an active code base).
While running dotnet ef dcontext scaffold --help I do not see any option to help remedy this either.
Reacted by escalonn, Olavo Rocha Neto, Jordan Nash, Asif ashraf, singha, observant, Eric Sellers, sibeliuz, Robin Pedersen, magicorb and 12 more
I will investigate adding the option to have the connectionstring removed to my "EF Core Power Tools" ErikEJ/SqlCeToolbox#582 - is the best approach to simply remove the 2 lines of code in OnConfiguring?
That's neat and I 100% appreciate it, but unfortunately most of our developers do not use Visual Studio proper anymore, we are mixed between Rider and VS Code (mostly for cross-platform support) :(.
@KallDrexx This was actually discussed at great length a few years ago. The problem is that we want the result of reverse engineering to be runnable. If it isn't then people tend to give up immediately. We also couldn't come up with a secure way of doing this that would work across platforms/environments/frameworks. So after much debate we went with putting the connection string in, but with a warning comment. This certainly isn't ideal, but as of now it seems the best compromise between the competing requirements.
Note that the work planned around update-model-from-database #831 should make this much less of a problem for your scenario because it will not be necessary to run a complete , new scaffolding every time.
Reacted by escalonn, Oleg M, Alex Zaytsev, Will 保哥, Eric Sellers, Cynthia MacLeod, Robin Pedersen, James Mallon, Leandro Bardelli, Simon Weaver and 6 more
For what it is worth, it seems to me the best compromise would have been to include an additional, optional flag that would result in the current behavior - and to have the default behavior be something that is suitable for use against a production code base.
The inclusion of the connection string is bad practice, and the tooling should work in a way that encourages people to wean themselves off of functionality that was included for the sake of mitigating any learning curve that may exist.
People following a guide can easily include a --hold-my-hand flag... they are probably copying and pasting from the web anyway. When present, the included warning comment should then advise them to remove that line of code, and omit the flag when they are ready to scaffold for use in a production environment.
It is discouraging to me that this isn't obvious, and that the current behavior is actually the product of intentional deliberation, rather than just an oversight.
Can we at least consider adding a flag to the CLI tool to prevent this behavior? The warning comment could be updated to inform developers of the option.
Reacted by escalonn, Alex Zaytsev, Yass, Eric Sellers, Alemar, Cynthia MacLeod, Jonathan Jones, Robert Lloyd, Kitty Chen, chris-clark-serverless and 2 more
The likelihood of someone coming to EF Core to just try it out and just stumbling on how to scaffold C# entities from an existing database without looking at any documentation seems pretty slim to me. If they are already following documentation to perform the scaffold I don't see why it's that difficult to instruct them how to pass a connection string to a DbContext. That's only one extra step they have to use to execute and gives them insight how to properly extract their connection string into a more secure area.
Reacted by escalonn, Yass, Alemar, Cynthia MacLeod and Leandro Bardelli
After looking at this more closely,
the very first code snippet is actually not what we are generating with 2.0 packages. #6686 explicitly converted code to following style.
protectedoverridevoidOnConfiguring(DbContextOptionsBuilderoptionsBuilder){if(!optionsBuilder.IsConfigured){
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
optionsBuilder.UseSqlServer(@"<connection string>");}}
Which makes sure that if the DbContext is configured already, it won't be reconfigured. So scaffolding actually does not change connection string and does not cause any issue of hitting wrong database. The problem does not exist actually.
Further, re-running scaffolding erases all custom modifications #831 fixes it. This is just one of the points of that issue.
It is quite ironic thread though.
Beginners should read whole documentation line by line but reading code reviews in detail is not necessary.
Beginners should learn to pass in extra flag as an extra step when removing 2 lines of code is huge step.
It is unacceptable to put connectionstring in code when it is acceptable to ignore warnings during the build time.
Reacted by Erik Ejlskov Jensen, Rafael Almeida, Scott Gartner, Vitor Miguel Correia, Olavo Rocha Neto, Alex Zaytsev, Mario Henrique Lopes Duarte and Robert Lloyd
Given that after removing OnConfiguring first time, "Update model from database" will preserve that modification as part of #831 and #831 being slated for 2.1.0 release, adding a flag in 2.1.0 release provides very little value.
What is ironic is you missed the part where nobody claimed beginners read documentation line-by-line, the assumption was made they are copy pasting. The warning should educate them on how to alleviate the concern instead of requiring them to remember to revisit to the same constructor every time they update their database outside of code-first.
What is ironic is that the content of the message also describes the security risks associated with having the connection string in the code, adding an if statement doesn't alleviate this concern whatsoever.
What is Ironic is you are referencing an issue that may resolve it which has been open now for what - 3 years? Also, if I'm not mistaken the 2.1 .net core sdk isn't even released yet?
Tooling should do predictable things, and hard-wiring the codebase to the reference database during scaffold is unpredictable. The current behavior causes issues for teams who don't use code first to manage their database (e.g. that have an actual DBA) and seems trivial to address (a PR has already been submitted). The sarcasm at the end of your post @smitpatel is unnecessary and IMO violates your own repository guidelines around decorum.
Reacted by Magnus Markling, Violin Iliev, dcb99, weirdyang, Eric Sellers, Leandro Bardelli, pchungpag, Robert Lloyd and Mehdi
@josh-sachs , I do not see sarcasm in the text @smitpatel , if you look, quotes being programmed to 2.1.
You have your opinion and your point of view, but I do not find your text productive. @smitpatel just wanted to show something, and I believe that when he asked the beginners to see the documentation, surely the intention was good and did not disqualify anyone!
to complement: @smitpatel is one of the people who help most here, I say that because the same, like everyone on the team, always point me in the right direction.
It's fine - I might just be having a bad day and took it the wrong way, but reading it still seems condescending. Perhaps sarcastic was the wrong word. I recognize that I have a tendency to get combative, so apologies for that.
Regardless there is, and apparently may continue to be an issue here for teams not using code-first to drive the database schema. My original text attempts to highlight the issue that appears to just be, at this point, symptomatic of the direction the framework appears to be moving in.
The PR submitted by Kalldrex proposes to alleviate it, so at this point there isn't much more to discuss. It is either determined to be a worthwhile inclusion or it isn't. I don't quite see how intentionally keeping the tooling ham stringed for this particular scenario benefits anyone, but that is just me and my opinion.
@josh-sachs , I'm sure the team will look at it with affection. I realized that these days they are working hard to improve many things and also make more implementations.
I'm following the Mysql Official documentation, wasting hours to solve this, so don't give us the "rtfm" because you are lazy to help lazy people. This is the law of the minor effort and you blame people that don't read but you neither write doc....
car project has a reference to car.entites
car project file "appsettings.json" has a "ConnectionStrings" named carDB
Located into "car.entites" directory I had generated entities inside car.entities library using this command: dotnet ef dbcontext scaffold "Server=DESKTOP-xxxxx\MSSQLSERVER_2019;Database=xxxx;User Id=xxx;Password=xxx;MultipleActiveResultSets=true" Microsoft.EntityFrameworkCore.SqlServer -o Models
It works perfect and I am able to display data from Database.
but I need to use the connectionString name instead to have the connectionString inside of my carDBContext file.
If I run this command form NuGet Administrator Console, inside my "car.entities" directory; it works perfect Scaffold-DbContext -Connection name=CarDB -OutputDir Models Microsoft.EntityFrameworkCore.SqlServer -force
But If I work with powerShell following the the same steps:
From powerShell inside my "car.entities" directory run this command: dotnet ef dbcontext scaffold Name=CarDB Microsoft.EntityFrameworkCore.SqlServer -o Models -f but the system cannot find the connectionString, the error message is:
A named connection string was used, but the name 'CarDB' 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.
How can I tell donet ef where to find my connection string name?
@Byron2016 I'm shooting from the hip but here are some thoughts.
You need to be in the main asp.net core mvc project car folder when you run dotnet ef using the Name=CarDB style of connection string. That project needs to be able to compile and must provide a connection string named CarDB via an appsettings file, user secrets, environment variable, etc.
Let's call main mvc project "car.webapp" for the sake of clarity. It sounds like you have a second project named "car.entities" that is beside the car.webapp. So your solution folder might look like this:
/path/to/solution/car/
car.entities/
Models/ <-- this is where the classes will be scaffolded
car.entities.csproj
car.webapp/
appsettings.json <-- this file contains { "ConnectionStrings": { "CarDB": "Server=..." } ... }
car.webapp.csproj
car.sln
With that structure you should be able to run the following commands.
cd /path/to/solution/car/car.webapp/
dotnet ef dbcontext scaffold Name=CarDB Microsoft.EntityFrameworkCore.SqlServer -o ../car.entities/Models/ -f
You will probably want to tweak the namespace. With the EF Core .NET 5 tooling you can provide a namespace argument like so:
Also there are times when I've scaffolded changes to the entities that make it so my main web application cannot compile. You may want to re-scaffold to undo or tweak your entities, but if the project that provides the named connection string cannot compile then the scaffolding can't run. One way to work around that is to have a project that is dedicated to providing the named connection string (and other design timestuff if you want) which does not depend on the project that contains the entities.
This comes back as a top search on google for things like: "dotnet ef scaffold avoid connection string" and I ended up reading a lot of a discussion which is now irrelevant, I hope this helps someone.
Reacted by Kitty Chen, Bouke Versteegh, Almir A. F. Junior, Marcin Malinowski, Juraj Ahel, Mehdi and Aleksei Melkor
This comes back as a top search on google for things like: "dotnet ef scaffold avoid connection string" and I ended up reading a lot of a discussion which is now irrelevant, I hope this helps someone.
@bobwah when i run with --no-onconfiguring it removes the warning and all but it also removes the default constructor which causes the build to fail. any idea why?
Activity
ErikEJ commentedon Nov 29, 2017
I will investigate adding the option to have the connectionstring removed to my "EF Core Power Tools" ErikEJ/SqlCeToolbox#582 - is the best approach to simply remove the 2 lines of code in OnConfiguring?
ErikEJ commentedon Nov 29, 2017
@KallDrexx Implemented in the latest daily build: https://github.com/ErikEJ/SqlCeToolbox/wiki/EF-Core-Power-Tools
KallDrexx commentedon Nov 29, 2017
That's neat and I 100% appreciate it, but unfortunately most of our developers do not use Visual Studio proper anymore, we are mixed between Rider and VS Code (mostly for cross-platform support) :(.
ajcvickers commentedon Nov 29, 2017
@KallDrexx This was actually discussed at great length a few years ago. The problem is that we want the result of reverse engineering to be runnable. If it isn't then people tend to give up immediately. We also couldn't come up with a secure way of doing this that would work across platforms/environments/frameworks. So after much debate we went with putting the connection string in, but with a warning comment. This certainly isn't ideal, but as of now it seems the best compromise between the competing requirements.
Note that the work planned around update-model-from-database #831 should make this much less of a problem for your scenario because it will not be necessary to run a complete , new scaffolding every time.
josh-sachs commentedon Nov 30, 2017
For what it is worth, it seems to me the best compromise would have been to include an additional, optional flag that would result in the current behavior - and to have the default behavior be something that is suitable for use against a production code base.
The inclusion of the connection string is bad practice, and the tooling should work in a way that encourages people to wean themselves off of functionality that was included for the sake of mitigating any learning curve that may exist.
People following a guide can easily include a
--hold-my-handflag... they are probably copying and pasting from the web anyway. When present, the included warning comment should then advise them to remove that line of code, and omit the flag when they are ready to scaffold for use in a production environment.It is discouraging to me that this isn't obvious, and that the current behavior is actually the product of intentional deliberation, rather than just an oversight.
Can we at least consider adding a flag to the CLI tool to prevent this behavior? The warning comment could be updated to inform developers of the option.
KallDrexx commentedon Nov 30, 2017
The likelihood of someone coming to EF Core to just try it out and just stumbling on how to scaffold C# entities from an existing database without looking at any documentation seems pretty slim to me. If they are already following documentation to perform the scaffold I don't see why it's that difficult to instruct them how to pass a connection string to a
DbContext. That's only one extra step they have to use to execute and gives them insight how to properly extract their connection string into a more secure area.Added scaffold line argument to not put connection string in dbcontext
smitpatel commentedon Nov 30, 2017
After looking at this more closely,
the very first code snippet is actually not what we are generating with 2.0 packages.
#6686 explicitly converted code to following style.
Which makes sure that if the DbContext is configured already, it won't be reconfigured. So scaffolding actually does not change connection string and does not cause any issue of hitting wrong database. The problem does not exist actually.
Further, re-running scaffolding erases all custom modifications #831 fixes it. This is just one of the points of that issue.
It is quite ironic thread though.
Beginners should read whole documentation line by line but reading code reviews in detail is not necessary.
Beginners should learn to pass in extra flag as an extra step when removing 2 lines of code is huge step.
It is unacceptable to put connectionstring in code when it is acceptable to ignore warnings during the build time.
smitpatel commentedon Nov 30, 2017
Given that after removing
OnConfiguringfirst time, "Update model from database" will preserve that modification as part of #831 and #831 being slated for 2.1.0 release, adding a flag in 2.1.0 release provides very little value.josh-sachs commentedon Nov 30, 2017
What is ironic is you missed the part where nobody claimed beginners read documentation line-by-line, the assumption was made they are copy pasting. The warning should educate them on how to alleviate the concern instead of requiring them to remember to revisit to the same constructor every time they update their database outside of code-first.
What is ironic is that the content of the message also describes the security risks associated with having the connection string in the code, adding an
ifstatement doesn't alleviate this concern whatsoever.What is Ironic is you are referencing an issue that may resolve it which has been open now for what - 3 years? Also, if I'm not mistaken the 2.1 .net core sdk isn't even released yet?
Tooling should do predictable things, and hard-wiring the codebase to the reference database during scaffold is unpredictable. The current behavior causes issues for teams who don't use code first to manage their database (e.g. that have an actual DBA) and seems trivial to address (a PR has already been submitted). The sarcasm at the end of your post @smitpatel is unnecessary and IMO violates your own repository guidelines around decorum.
ralmsdeveloper commentedon Nov 30, 2017
@josh-sachs , I do not see sarcasm in the text @smitpatel , if you look, quotes being programmed to 2.1.
You have your opinion and your point of view, but I do not find your text productive.
@smitpatel just wanted to show something, and I believe that when he asked the beginners to see the documentation, surely the intention was good and did not disqualify anyone!
to complement: @smitpatel is one of the people who help most here, I say that because the same, like everyone on the team, always point me in the right direction.
josh-sachs commentedon Nov 30, 2017
It's fine - I might just be having a bad day and took it the wrong way, but reading it still seems condescending. Perhaps sarcastic was the wrong word. I recognize that I have a tendency to get combative, so apologies for that.
Regardless there is, and apparently may continue to be an issue here for teams not using code-first to drive the database schema. My original text attempts to highlight the issue that appears to just be, at this point, symptomatic of the direction the framework appears to be moving in.
The PR submitted by Kalldrex proposes to alleviate it, so at this point there isn't much more to discuss. It is either determined to be a worthwhile inclusion or it isn't. I don't quite see how intentionally keeping the tooling ham stringed for this particular scenario benefits anyone, but that is just me and my opinion.
ralmsdeveloper commentedon Nov 30, 2017
@josh-sachs , I'm sure the team will look at it with affection. I realized that these days they are working hard to improve many things and also make more implementations.
Your feedback is certainly valuable to the team!
32 remaining items
leanbardelli commentedon Sep 20, 2020
I'm following the Mysql Official documentation, wasting hours to solve this, so don't give us the "rtfm" because you are lazy to help lazy people. This is the law of the minor effort and you blame people that don't read but you neither write doc....
asilverstein commentedon Sep 29, 2020
Please tell us what is the name of the command line option?
jeremycook commentedon Sep 30, 2020
@asilverstein The option is
--no-onconfiguringif you are scaffolding with the EF Core CLI, and-NoOnConfiguringif you are scaffolding with PowerShell from the Package Manager Console. Watch out for comments like "Added in EF Core 5.0" in the docs. I've seen some folks confused because they were trying out a new option (like this one) with an older CLI (i.e. 3.1 and earlier).Byron2016 commentedon Oct 31, 2020
My project is structured in this way:
car project has a reference to car.entites
car project file "appsettings.json" has a "ConnectionStrings" named carDB
Located into "car.entites" directory I had generated entities inside car.entities library using this command:
dotnet ef dbcontext scaffold "Server=DESKTOP-xxxxx\MSSQLSERVER_2019;Database=xxxx;User Id=xxx;Password=xxx;MultipleActiveResultSets=true" Microsoft.EntityFrameworkCore.SqlServer -o ModelsIt works perfect and I am able to display data from Database.
but I need to use the connectionString name instead to have the connectionString inside of my carDBContext file.
If I run this command form NuGet Administrator Console, inside my "car.entities" directory; it works perfect
Scaffold-DbContext -Connection name=CarDB -OutputDir Models Microsoft.EntityFrameworkCore.SqlServer -forceBut If I work with powerShell following the the same steps:
From powerShell inside my "car.entities" directory run this command:
dotnet ef dbcontext scaffold Name=CarDB Microsoft.EntityFrameworkCore.SqlServer -o Models -fbut the system cannot find the connectionString, the error message is:A named connection string was used, but the name 'CarDB' 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.
How can I tell donet ef where to find my connection string name?
jeremycook commentedon Nov 3, 2020
@Byron2016 I'm shooting from the hip but here are some thoughts.
You need to be in the main asp.net core mvc project car folder when you run dotnet ef using the Name=CarDB style of connection string. That project needs to be able to compile and must provide a connection string named CarDB via an appsettings file, user secrets, environment variable, etc.
Let's call main mvc project "car.webapp" for the sake of clarity. It sounds like you have a second project named "car.entities" that is beside the car.webapp. So your solution folder might look like this:
With that structure you should be able to run the following commands.
You will probably want to tweak the namespace. With the EF Core .NET 5 tooling you can provide a namespace argument like so:
Also there are times when I've scaffolded changes to the entities that make it so my main web application cannot compile. You may want to re-scaffold to undo or tweak your entities, but if the project that provides the named connection string cannot compile then the scaffolding can't run. One way to work around that is to have a project that is dedicated to providing the named connection string (and other design time stuff if you want) which does not depend on the project that contains the entities.
RaulGarciaCarrillo commentedon Nov 8, 2020
I'm ussing --no-onconfiguring flag with version EF Core 5.0.0-rc.2.20475.6, but it's still creating method OnConfiguring
ajcvickers commentedon Nov 8, 2020
@RaulGarciaCarrillo Make sure you have the 5.0-rc2 dotnet-ef tool and have the 5.0-rc2 EF Core packages referenced in your projects.
RaulGarciaCarrillo commentedon Nov 8, 2020
@ajcvickers Thanks! That was the problem
bobwah commentedon Mar 4, 2022
TLDR;
There is now a flag:
--no-onconfiguring
This comes back as a top search on google for things like: "dotnet ef scaffold avoid connection string" and I ended up reading a lot of a discussion which is now irrelevant, I hope this helps someone.
KittyChen913 commentedon May 12, 2022
It works for me, thanks.
ci-vamp commentedon Apr 25, 2023
@bobwah when i run with --no-onconfiguring it removes the warning and all but it also removes the default constructor which causes the build to fail. any idea why?