Claudio Torres
Claudio Torres

Reputation: 63

Entity Core 2.0 - OnConfiguring not working with Configuration.GetConnectionString("DefaultConnection")

For tome reason that I can't explain, the entity migrations don't work if I get connectionstring in appsettings.json but If I put It hardcoded, it works. I printed the connectionstring in console and it's the same but I receive and connection error with that one.

WORKS

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseSqlServer("Data Source=WIN10-VM;Initial Catalog=ContaApp;Integrated Security=false;User=adm;Password=123456");            
}

NOT WORKING

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseSqlServer(_configuration.GetConnectionString("DefaultConnection");
}

EDIT: The error is:

An error occurred using the connection to database 'ContaApp' on server 'WIN-10VM'.
System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) ---> System.ComponentModel.Win32Exception (0x80004005): The network path was not found
   at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling)
   at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionPool.WaitForPendingOpen()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.<OpenAsync>d__34.MoveNext()
ClientConnectionId:00000000-0000-0000-0000-000000000000
Error Number:53,State:0,Class:20

It happens several times on dotnet ef database update

Same error using IDesignTimeDbContextFactory

public class ContaAppContextFactory : IDesignTimeDbContextFactory<ContaAppContext>
{
    public ContaAppContext CreateDbContext(string[] args)
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: true, reloadOnChange: true)
            .Build();

        var builder = new DbContextOptionsBuilder<ContaAppContext>();

        var connectionString = configuration.GetConnectionString("DefaultConnection");
        Console.WriteLine($"********************************\n{connectionString}\n**********************************");


        builder.UseSqlServer(connectionString);

        return new ContaAppContext(builder.Options);
    }
}

Upvotes: 0

Views: 1555

Answers (1)

Tseng
Tseng

Reputation: 64229

Your appsettings.json is wrong.

It must look something like

{
  "ConnectionStrings": {
    "DefaultConnection": "..."
  }
}

Because _configuration.GetConnectionString("DefaultConnection")) is a shorthand for _configuration["ConnectionStrings:DefaultConnection"]. That's why

optionsBuilder.UseSqlServer("Data Source=WIN10-VM;Initial Catalog=ContaApp;Integrated Security=false;User=adm;Password=123456");

works for you but not from configuration.

Upvotes: 1

Related Questions