2

I'm using .NET 7 with Entity Framework Core 7.0.9.

I'm using a third party CMS (in case this makes any difference). I have the usual structure for this project where I have

  • Core - All domain classes
  • Infrastructure - CRUD operations
  • Web - 3rd party CMS

After a few errors and installing additional packages as required by the error message I enabled Migrations and created my first Migration. A class was created against the Infrastructure project.

I had to set Web as the startup project.

I then run Update-Database and get this error

The ConnectionString property has not been initialized.

which is where I'm stuck at. Here is a breakdown of the project and code

Core

public class ProjectContext : DbContext
{
    public ProjectContext()
    {
    }

    public projectContext(DbContextOptions<DataContext> options)
        : base(options)
    {
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        IConfiguration _config = new ConfigurationManager();
        optionsBuilder.UseSqlServer(_config.GetConnectionString("customSectionConnectionStringName"));
        base.OnConfiguring(optionsBuilder);
    }

    // All DbSets 
}

In the appsettings.json, I have this config:

"ConnectionStrings": {
    "WebCms": "Server=ABC",
    "WebCms_ProviderName": "Microsoft.Data.SqlClient",
    "customSectionConnectionStringName": "Server=ABC...Another Database",
    "customSectionConnectionStringName_ProviderName": "Microsoft.Data.SqlClient"
}

I enabled Verbose logging when running Update-Database -Verbose, which produced the following

configuration Debug --working-dir C:\Project --root-namespace Infrastructure --nullable
Using assembly 'Infrastructure'.
Using startup assembly 'Web'.
Using application base 'C:\Project\Web\bin\Debug\net7.0'.
Using working directory 'C:\Project\Web'.
Using root namespace 'Infrastructure'.
Using project directory 'C:\Project\Infrastructure\'.
Remaining arguments: .
Finding DbContext classes...
Finding IDesignTimeDbContextFactory implementations...
Finding application service provider in assembly 'Web'...
Finding Microsoft.Extensions.Hosting service provider...
Using environment 'Development'.
Using application service provider from Microsoft.Extensions.Hosting.
Found DbContext 'DataContext'.
Finding DbContext classes in the project...
Using context 'DataContext'.
Finding design-time services referenced by assembly 'Web'...
Finding design-time services referenced by assembly 'Infrastructure'...
No referenced design-time services were found.
Finding design-time services for provider 'Microsoft.EntityFrameworkCore.SqlServer'...
Using design-time services from provider 'Microsoft.EntityFrameworkCore.SqlServer'.
Finding IDesignTimeServices implementations in assembly 'Web'...
No design-time services were found.
System.InvalidOperationException: The ConnectionString property has not been initialized.
   at Microsoft.Data.SqlClient.SqlConnection.PermissionDemand()
   at Microsoft.Data.SqlClient.SqlConnectionFactory.PermissionDemand(DbConnection outerConnection)
   at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at Microsoft.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry, SqlConnectionOverrides overrides)
   at Microsoft.Data.SqlClient.SqlConnection.Open(SqlConnectionOverrides overrides)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerConnection.OpenDbConnection(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternal(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.<>c__DisplayClass18_0.<Exists>b__0(DateTime giveUp)
   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.<>c__DisplayClass12_0`2.<Execute>b__0(DbContext _, TState s)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func`2 operation, Func`2 verifySucceeded)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.Exists(Boolean retryOnNotExists)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String connectionString, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String connectionString, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)

No matter what I've tried, I keep getting that error:

The ConnectionString property has not been initialized

I finally added

services.AddDbContext<DataContext>(options => options.UseSqlServer(_config.GetConnectionString("customSectionConnectionStringName")));

to the ConfigureService section of the CMS but I still get the same error.

Does anyone have any ideas how to overcome this error?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • See https://stackoverflow.com/questions/29110241/how-do-you-configure-the-dbcontext-when-creating-migrations-in-entity-framework – jdweng Jul 14 '23 at 15:59

1 Answers1

3
  1. Verify that correct startup project is selected in the VS (I assume you are using that and running command from the Package Manager Console, otherwise provide appropriate -StartupProject parameter).

  2. IConfiguration _config = new ConfigurationManager(); (it will be "empty" so _config.GetConnectionString("customSectionConnectionStringName") will return null) is not a way to read configs "manually" in .NET nowadays. You need to do at least something like the following:

    var cfgBuilder = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile(...); // add other providers if needed
    
    var _config = cfgBuildeR.Build();
    
  3. You should avoid performing such setup in DbContext.OnConfiguring and move that to the "consumer" code (composition root) so you can leverage the DI (i.e. services.AddDbContext<DataContext>(...)). But when you will do that - do not forget to remove the setup from OnConfiguring (or at least wrap it in if (!optionsBuilder.IsConfigured)).

Read more:

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • The OP issue is the connection string and your solution does not address the connection string. – jdweng Jul 14 '23 at 16:00
  • @jdweng I' think it does. The problem I see is that `Configuration _config = new ConfigurationManager()` is empty and when is requested it provides null hence the _"The ConnectionString property has not been initialized."_ error. So points 2 or 3 should handle that. – Guru Stron Jul 14 '23 at 16:02
  • 1
    I removed the code under OnConfiguring and left the DI code (services.AddDbContext.... ) as it was and that resolved the issue. The command in package manager ran successfully. I'll mark this as the answer. I will also go over the links posted but is there another resource/tutorial that gives the equivalent changes from the 'old' to the new .Net 6/7 way? – KeithViking Jul 14 '23 at 19:15
  • @KeithViking there were a lot of changes (though quite a lot of ideas are in general the same). You can try looking into [Upgrade from ASP.NET Framework to ASP.NET Core](https://learn.microsoft.com/en-us/aspnet/core/migration/proper-to-2x/?view=aspnetcore-7.0) – Guru Stron Jul 17 '23 at 12:57