Entity Core 2.0 - OnConfiguring不使用Configuration.GetConnectionString(“DefaultConnection”)

时间:2017-09-27 21:54:05

标签: asp.net-core entity-framework-core

由于我无法解释的原因,如果我在appsettings.json中获取了连接字符串,则实体迁移不起作用但是如果我将其硬编码,则可以正常工作。 我在控制台中打印了连接字符串并且它是相同的,但我收到了连接错误。

工作

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

不工作

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

编辑: 错误是:

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

在dotnet ef数据库更新

上发生了几次

使用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);
    }
}

1 个答案:

答案 0 :(得分:1)

您的appsettings.json错了。

看起来像

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

因为_configuration.GetConnectionString("DefaultConnection"))_configuration["ConnectionStrings:DefaultConnection"]的简写。这就是

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

适合您,但不适合配置。