【发布时间】:2017-01-07 10:02:34
【问题描述】:
我正在尝试连接到 Azure SQL,但出现错误 The underlying provider failed on Open
我发现我把连接字符串放在了错误的app.config - 把它移到了可执行项目的app.config,但结果还是一样
当我检查 ConfigurationManager.ConnectionStrings["AzureDatabase"] 时,它返回 null。当我尝试连接时,它只使用默认的 SQLExpress。
当我检查我的可执行应用程序的构建文件夹时 - 有一个带有“AzureDatabase”的<app_name>.exe.config 文件。我不知道从哪里搜索
这是我的 DbContext 类
[DbConfigurationType(typeof(AzureDbConfiguration))]
public class ProductDbContext : DbContext
{
//Db sets
static MyContext()
{
//I don't want to change database from code
Database.SetInitializer<MyContext>(null);
}
public MyContext() : base("AzureDatabase") //this is my connectionstring
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//some mappings
}
}
这是 AzureDbConfiguration
public class AzureDbConfiguration : DbConfiguration
{
public AzureDbConfiguration()
{
SetExecutionStrategy("System.Data.SqlClient", () => new SqlAzureExecutionStrategy(2, TimeSpan.FromSeconds(10)));
}
}
这是我的 app.config 文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="AzureDatabase"
connectionString="Server=tcp:xxx.database.windows.net,1433;Initial Catalog=xxx;Persist Security Info=False;User ID=xxxx;Password=xxxxx;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" providerName="System.Data.SqlClient"/>
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>
您有什么想法吗?
【问题讨论】:
-
您将连接字符串命名为
AzureDatabase并正在检查ConfigurationManager.ConnectionStrings["MyConnectionString"]?这命名不对齐吗?如果您将其命名为DefaultConnection,它是否有效? -
@drediske 啊,对不起 - 它是
AzureDatabase而不是MyConnectionString。更新了我的帖子...
标签: connection-string azure-sql-database app-config