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

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

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

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

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

我可以通过 Visual Studio Codemssql 扩展成功连接并查询 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 数据库更新

最后,我收到以下错误:

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 数据库更新 命令时却无法连接。

最佳答案

您可以尝试以下几件事:

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

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

关于c# - 如何将.Net Core应用程序连接到Azure SQL数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42940901/

相关文章:

c# - 将 PictureBox 图像插入到 Sql Server 数据库中

c# - 在 Multi-Tenancy 环境中更快地加载 NHibernate

sql - 什么会导致 SSIS 忽略包配置连接?

sql - 根据前几天的计算进行递归计算

c# - 如何编辑所有特殊 html 标签的属性(如 a)

c# - 使用接口(interface)属性实现的接口(interface)

c# - System.Web.HttpContextBase' 不包含带有 Elmah 日志记录的 'Current' MVC 4 的定义

c# - 如何访问 Task.Factory.StartNew 中的 HttpContext.Current?

.net - XML 省略号/其他语法 - 它叫什么?

c# - x64 SQL Server 检测网络实例名称