如何将.Net Core应用程序连接到Azure SQL数据库

时间:2017-03-22 01:00:10

标签: c# .net sql-server entity-framework azure

我创建了一个空的Azure SQL数据库。

我已将我的IP添加到服务器上的防火墙设置中。

我希望EF Core使用命令dotnet ef database update为我创建数据库。

我可以通过 Visual Studio代码mssql分机成功连接并查询Azure数据库。

我尝试使用连接字符串将应用程序连接到数据库,并将连接字符串直接放入Startup.cs文件中。

appsettings.json

{
"Logging": {
    "IncludeScopes": false,
    "LogLevel": {
    "Default": "Warning"
}
},
"ConnectionStrings": {
    "Development": "Server=tcp:appName.database.windows.net,1433;Initial Catalog=AppName;Persist Security Info=False;User ID=User;Password=Password;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
}
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc();

        // Add database services.
        services.AddDbContext<ApplicationContext>(options => 
            options.UseSqlServer(Configuration.GetConnectionString("Development")));
    }

我运行dotnet restore然后dotnet ef database update

最后,我收到以下错误:

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: TCP 
Provider, error: 35 - An internal exception was caught)

我错过了什么吗?我还能尝试什么?

编辑:我甚至尝试过不同的位置(不同的IP地址)。我将其添加到Azure中的防火墙设置中,得到了相同的结果。我可以通过VSCode中的 mssql扩展连接,但不能在我运行dotnet ef database update命令时连接。

2 个答案:

答案 0 :(得分:1)

您可以尝试以下几点:

  1. 确保您机器上的防火墙 允许1433的出站连接

  2. 您确定在Azure防火墙规则中使用了正确的IP地址吗?作为测试,您可以创建ip范围从1.1.1.1到255.255.255.255的规则,看看它是否有效。如果是,则表示您在Azure防火墙中提供了错误的IP

答案 1 :(得分:0)

运行dotnet ef database update --verbose显示该应用正在尝试连接到默认的blogging.db数据库。我发现它仍然列在 ApplicationContext.cs 中的OnConfiguring重写函数中。

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Data Source=blogging.db");
    }

在这里设置了合适的数据库后,一切都开始工作了。