DbContext OnConfiguring doesn't check IsConfigured for EF7 reverse engineer
See original GitHub issueEF Core 7 reverse engineer doesn’t check, if DbContextOptionsBuilder is already configured.
Steps to reproduce
Reverse Engineering of a Sql Server table into a DotNet 7 library.
After enabling the option “include connection string in generated code”, a method “OnConfiguring” is added to the generated context class.
Code of this method depends on selection at the first wizard screen (EF Core 6 / EF Core 7).
For EF Core 7, it isn’t checked anymore, if the DbContextOptionsBuilder is already configured.
This is not correct, as the method always configures SqlServer.
This will fail, if the context class is used together with another provider, e.g. during unit tests.
For me, a workaround is to disable the option “include connection string…” as I don’t need it.
But I think, the default behavior was “enabled” in some older versions of EF Core Power Tools.
// code for EF Core 6:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("...");
}
}
// code for EF Core 7:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.UseSqlServer("...");
Technical details
- EF Core version in use: EF Core 7
- Is Handlebars used: no
- Is T4 used: no
- Is .dacpac used: no
- EF Core Power Tools version: 2.5.1258
- Database engine: SQL Server 2019
- Visual Studio version: 2022 17.4.3
Issue Analytics
- State:
- Created 9 months ago
- Comments:9 (4 by maintainers)
Top GitHub Comments
Oh god, some really messed up thinking in here. A couple of reasons why this was a terrible decision:
OnConfiguring
and theDbContextOptionsBuilder
instanceThis is not the first time it seems as though the EF team lives in its own bubble, ignorant of other .NET parts.
The result: globally and universally wasted developer time.
@bricelam @ErikEJ It’s because the idea that you would configure the database provider inside your DbContext in some cases, but only if the context is not configured already, isn’t generally useful. Also, it means that people may leave the configuration in OnConfiguring in their context when it isn’t being used, possibly even with a connection string in it. So, if you’re not using OnConfiguring for this, then pass the flag
--no-onconfiguring
. And if you really want both, then a) tell us why; I’m interested! and b) use the T4 template to do it.