dotnet / efcore

EF Core is a modern object-database mapper for .NET. It supports LINQ queries, change tracking, updates, and schema migrations.
https://docs.microsoft.com/ef/
MIT License
13.79k stars 3.19k forks source link

EF core tools is ignoring appsetttings.Development.json #19585

Closed aliensqueegee closed 2 years ago

aliensqueegee commented 4 years ago

Using Package Manager Console from Visual Studio, I want to add initial migration and update the database. I'm using basic dotnet core console application. Running Update-Database command in Package Manager Console fails.

Steps to reproduce

Create default .net core 3.1 console application in VS 2019.

csproj

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Hosting" Version="3.1.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.0">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.0">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
  </ItemGroup>

  <ItemGroup>
    <None Update="appsettings.Development.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
    <None Update="appsettings.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
  </ItemGroup>
</Project>

appsettings.json

{
  "ConnectionStrings": {
    "TestContext": "data source=; initial catalog=; USER ID=; PASSWORD=; MultipleActiveResultSets=true; Persist Security Info=true; App=EntityFramework;"
  }
}

appsettings.Development.json

{
  "ConnectionStrings": {
    "TestContext": "data source=localhost; initial catalog=Test; USER ID=fakeuser; PASSWORD=fakepassword; MultipleActiveResultSets=true; Persist Security Info=true; App=EntityFramework;"
  }
}

launchSettings.json

{
  "profiles": {
    "GenericHostEFCoreMigrations": {
      "commandName": "Project",
      "environmentVariables": {
        "DOTNET_ENVIRONMENT": "Development"
      }
    }
  }
}

Program.cs

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Threading.Tasks;

namespace GenericHostEFCoreMigrations
{
    class Program
    {
        static async Task Main(string[] args)
        {
            try
            {
                await CreateHostBuilder(args).Build().RunAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                 .ConfigureServices((hostContext, services) =>
                 {
                     string connectionString = hostContext.Configuration.GetConnectionString("TestContext");

                     services.AddDbContext<TestContext>(options => options.UseSqlServer(connectionString));
                 });

        public class TestContext : DbContext
        {
            public DbSet<Person> People { get; set; }

            public TestContext(DbContextOptions<TestContext> options) : base(options) { }

            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                modelBuilder.Entity<Person>().HasKey(p => p.Id);
                modelBuilder.Entity<Person>().Property(p => p.Name).IsRequired().HasMaxLength(64);
                modelBuilder.Entity<Person>().Property(p => p.Age).IsRequired();
            }
        }

        public class Person
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public int Age { get; set; }
        }

  //public class ELTContextFactory : IDesignTimeDbContextFactory<TestContext>
        //{
        //    public TestContext CreateDbContext(string[] args)
        //    {
        //        IHost host = Program.CreateHostBuilder(null).Build();
        //        IConfiguration configuration = host.Services.GetRequiredService<IConfiguration>();
        //        string connectionString = configuration.GetConnectionString("TestContext");
        //        DbContextOptionsBuilder<TestContext> optionBuilder = new DbContextOptionsBuilder<TestContext>();
        //        optionBuilder.UseSqlServer(connectionString);

        //        return new TestContext(optionBuilder.Options);
        //    }
        //}
    }
}

Running Add-Migration with IDesignTimeDbContextFactory commented generates

PM> Add-Migration Initial -Verbose
Using project 'GenericHostEFCoreMigrations'.
Using startup project 'GenericHostEFCoreMigrations'.
Build started...
Build succeeded.
C:\Program Files\dotnet\dotnet.exe exec --depsfile C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations\bin\Debug\netcoreapp3.1\GenericHostEFCoreMigrations.deps.json --additionalprobingpath C:\Users\stefan.simion\.nuget\packages --additionalprobingpath "C:\Program Files\dotnet\sdk\NuGetFallbackFolder" --runtimeconfig C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations\bin\Debug\netcoreapp3.1\GenericHostEFCoreMigrations.runtimeconfig.json C:\Users\stefan.simion\.nuget\packages\microsoft.entityframeworkcore.tools\3.1.0\tools\netcoreapp2.0\any\ef.dll migrations add Initial --json --verbose --no-color --prefix-output --assembly C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations\bin\Debug\netcoreapp3.1\GenericHostEFCoreMigrations.dll --startup-assembly C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations\bin\Debug\netcoreapp3.1\GenericHostEFCoreMigrations.dll --project-dir C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations\ --language C# --working-dir C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations --root-namespace GenericHostEFCoreMigrations
Using assembly 'GenericHostEFCoreMigrations'.
Using startup assembly 'GenericHostEFCoreMigrations'.
Using application base 'C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations\bin\Debug\netcoreapp3.1'.
Using working directory 'C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations'.
Using root namespace 'GenericHostEFCoreMigrations'.
Using project directory 'C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations\'.
Finding DbContext classes...
Finding IDesignTimeDbContextFactory implementations...
Finding application service provider...
Finding Microsoft.Extensions.Hosting service provider...
Using environment 'Development'.
Using application service provider from Microsoft.Extensions.Hosting.
Found DbContext 'TestContext'.
Finding DbContext classes in the project...
Using context 'TestContext'.
Microsoft.EntityFrameworkCore.Infrastructure[10403]
      Entity Framework Core 3.1.0 initialized 'TestContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None
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 'GenericHostEFCoreMigrations'.
No referenced design-time services were found.
Finding IDesignTimeServices implementations in assembly 'GenericHostEFCoreMigrations'...
No design-time services were found.
Writing migration to 'C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations\Migrations\20200114142046_Initial.cs'.
Writing model snapshot to 'C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations\Migrations\TestContextModelSnapshot.cs'.
To undo this action, use Remove-Migration.

And Update-Database with IDesignTimeDbContextFactory commented generates

PM> Update-Database -Verbose
Using project 'GenericHostEFCoreMigrations'.
Using startup project 'GenericHostEFCoreMigrations'.
Build started...
Build succeeded.
C:\Program Files\dotnet\dotnet.exe exec --depsfile C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations\bin\Debug\netcoreapp3.1\GenericHostEFCoreMigrations.deps.json --additionalprobingpath C:\Users\stefan.simion\.nuget\packages --additionalprobingpath "C:\Program Files\dotnet\sdk\NuGetFallbackFolder" --runtimeconfig C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations\bin\Debug\netcoreapp3.1\GenericHostEFCoreMigrations.runtimeconfig.json C:\Users\stefan.simion\.nuget\packages\microsoft.entityframeworkcore.tools\3.1.0\tools\netcoreapp2.0\any\ef.dll database update --verbose --no-color --prefix-output --assembly C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations\bin\Debug\netcoreapp3.1\GenericHostEFCoreMigrations.dll --startup-assembly C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations\bin\Debug\netcoreapp3.1\GenericHostEFCoreMigrations.dll --project-dir C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations\ --language C# --working-dir C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations --root-namespace GenericHostEFCoreMigrations
Using assembly 'GenericHostEFCoreMigrations'.
Using startup assembly 'GenericHostEFCoreMigrations'.
Using application base 'C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations\bin\Debug\netcoreapp3.1'.
Using working directory 'C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations'.
Using root namespace 'GenericHostEFCoreMigrations'.
Using project directory 'C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations\'.
Finding DbContext classes...
Finding IDesignTimeDbContextFactory implementations...
Finding application service provider...
Finding Microsoft.Extensions.Hosting service provider...
Using environment 'Development'.
Using application service provider from Microsoft.Extensions.Hosting.
Found DbContext 'TestContext'.
Finding DbContext classes in the project...
Using context 'TestContext'.
Microsoft.EntityFrameworkCore.Infrastructure[10403]
      Entity Framework Core 3.1.0 initialized 'TestContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None
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 'GenericHostEFCoreMigrations'.
No referenced design-time services were found.
Finding IDesignTimeServices implementations in assembly 'GenericHostEFCoreMigrations'...
No design-time services were found.
Microsoft.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 (2): The system cannot find the file specified.
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken, DbConnectionPool pool, SqlAuthenticationProviderManager sqlAuthProviderManager)
   at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
   at Microsoft.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
   at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at Microsoft.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
   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)
   at Microsoft.Data.SqlClient.SqlConnection.Open()
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnection(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 c, 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.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func`2 operation)
   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 contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
ClientConnectionId:00000000-0000-0000-0000-000000000000
Error Number:2,State:0,Class:20
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)

Running Add-Migration with IDesignTimeDbContextFactory uncommented generates

PM> Add-Migration Initial -Verbose
Using project 'GenericHostEFCoreMigrations'.
Using startup project 'GenericHostEFCoreMigrations'.
Build started...
Build succeeded.
C:\Program Files\dotnet\dotnet.exe exec --depsfile C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations\bin\Debug\netcoreapp3.1\GenericHostEFCoreMigrations.deps.json --additionalprobingpath C:\Users\stefan.simion\.nuget\packages --additionalprobingpath "C:\Program Files\dotnet\sdk\NuGetFallbackFolder" --runtimeconfig C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations\bin\Debug\netcoreapp3.1\GenericHostEFCoreMigrations.runtimeconfig.json C:\Users\stefan.simion\.nuget\packages\microsoft.entityframeworkcore.tools\3.1.0\tools\netcoreapp2.0\any\ef.dll migrations add Initial --json --verbose --no-color --prefix-output --assembly C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations\bin\Debug\netcoreapp3.1\GenericHostEFCoreMigrations.dll --startup-assembly C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations\bin\Debug\netcoreapp3.1\GenericHostEFCoreMigrations.dll --project-dir C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations\ --language C# --working-dir C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations --root-namespace GenericHostEFCoreMigrations
Using assembly 'GenericHostEFCoreMigrations'.
Using startup assembly 'GenericHostEFCoreMigrations'.
Using application base 'C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations\bin\Debug\netcoreapp3.1'.
Using working directory 'C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations'.
Using root namespace 'GenericHostEFCoreMigrations'.
Using project directory 'C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations\'.
Finding DbContext classes...
Finding IDesignTimeDbContextFactory implementations...
Found IDesignTimeDbContextFactory implementation 'ELTContextFactory'.
Found DbContext 'TestContext'.
Finding application service provider...
Finding Microsoft.Extensions.Hosting service provider...
Using environment 'Development'.
Using application service provider from Microsoft.Extensions.Hosting.
Finding DbContext classes in the project...
Using DbContext factory 'ELTContextFactory'.
Using context 'TestContext'.
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 'GenericHostEFCoreMigrations'.
No referenced design-time services were found.
Finding IDesignTimeServices implementations in assembly 'GenericHostEFCoreMigrations'...
No design-time services were found.
DetectChanges starting for 'TestContext'.
DetectChanges completed for 'TestContext'.
Writing migration to 'C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations\Migrations\20200114142545_Initial.cs'.
Writing model snapshot to 'C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations\Migrations\TestContextModelSnapshot.cs'.
'TestContext' disposed.
To undo this action, use Remove-Migration.

Running Update-Migration with IDesignTimeDbContextFactory uncommented generates

PM> Update-Database -Verbose
Using project 'GenericHostEFCoreMigrations'.
Using startup project 'GenericHostEFCoreMigrations'.
Build started...
Build succeeded.
C:\Program Files\dotnet\dotnet.exe exec --depsfile C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations\bin\Debug\netcoreapp3.1\GenericHostEFCoreMigrations.deps.json --additionalprobingpath C:\Users\stefan.simion\.nuget\packages --additionalprobingpath "C:\Program Files\dotnet\sdk\NuGetFallbackFolder" --runtimeconfig C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations\bin\Debug\netcoreapp3.1\GenericHostEFCoreMigrations.runtimeconfig.json C:\Users\stefan.simion\.nuget\packages\microsoft.entityframeworkcore.tools\3.1.0\tools\netcoreapp2.0\any\ef.dll database update --verbose --no-color --prefix-output --assembly C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations\bin\Debug\netcoreapp3.1\GenericHostEFCoreMigrations.dll --startup-assembly C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations\bin\Debug\netcoreapp3.1\GenericHostEFCoreMigrations.dll --project-dir C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations\ --language C# --working-dir C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations --root-namespace GenericHostEFCoreMigrations
Using assembly 'GenericHostEFCoreMigrations'.
Using startup assembly 'GenericHostEFCoreMigrations'.
Using application base 'C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations\bin\Debug\netcoreapp3.1'.
Using working directory 'C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations'.
Using root namespace 'GenericHostEFCoreMigrations'.
Using project directory 'C:\Users\stefan.simion\source\repos\PoCs\GenericHostEFCoreMigrations\GenericHostEFCoreMigrations\'.
Finding DbContext classes...
Finding IDesignTimeDbContextFactory implementations...
Found IDesignTimeDbContextFactory implementation 'ELTContextFactory'.
Found DbContext 'TestContext'.
Finding application service provider...
Finding Microsoft.Extensions.Hosting service provider...
Using environment 'Development'.
Using application service provider from Microsoft.Extensions.Hosting.
Finding DbContext classes in the project...
Using DbContext factory 'ELTContextFactory'.
Using context 'TestContext'.
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 'GenericHostEFCoreMigrations'.
No referenced design-time services were found.
Finding IDesignTimeServices implementations in assembly 'GenericHostEFCoreMigrations'...
No design-time services were found.
Migrating using database '' on server ''.
Opening connection to database '' on server ''.
An error occurred using the connection to database '' on server ''.
'TestContext' disposed.
Microsoft.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 (2): The system cannot find the file specified.
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken, DbConnectionPool pool, SqlAuthenticationProviderManager sqlAuthProviderManager)
   at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
   at Microsoft.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
   at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at Microsoft.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
   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)
   at Microsoft.Data.SqlClient.SqlConnection.Open()
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnection(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 c, 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.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func`2 operation)
   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 contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
ClientConnectionId:00000000-0000-0000-0000-000000000000
Error Number:2,State:0,Class:20
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)

Further technical details

EF Core version: 3.1 Database provider: Microsoft.EntityFrameworkCore.SqlServer 3.1 Target framework: NET Core 3.1 Operating system: Windows 10 IDE: Visual Studio 2019 16.4.2

ajcvickers commented 4 years ago

Duplicate of #8695

aliensqueegee commented 4 years ago

@ajcvickers #8695 made me understand that at the moment EF Core tools don't have a proper way to read launchSettings.json file. If I'm running same code I posted in the original question into a ASP.NET Core Web Application, EF Core tools are successfully adding a migration and update the database (works with/without IDesignTimeDbContextFactory as well). So running same code in a console application doesn't work, but if I use a ASP.NET Core Web Application works fine. Any thought on this topic?

GenericHostEFCoreMigrations.zip

pastore commented 4 years ago

Hi all,

I don't understand why this ticket is closed. Author of the ticket says about appsetttings.Development.json file, but in supposedly duplicate ticket is said about launchSettings.json. Guys, they are not the same as you can guess. So at this moment, we can not take data from the configuration file, we have to set a hard code connection string. It is definitely great.

Thanks.

ajcvickers commented 4 years ago

@pastore They are duplicates because they have the same root cause. If you have a bug that you think has a different root cause, then pleas open a new issue and please attach a small, runnable project or post a small, runnable code listing that reproduces what you are seeing so that we can investigate.

pastore commented 4 years ago

@ajcvickers Thanks

saliksaly commented 10 months ago

It is possible to implement IDesignTimeDbContextFactory which can then read connection string from appsettings.Development.json. Here is how: