azure - 如何使用标准 dotnet Web 模板连接到 Azure 数据库

标签 azure asp.net-core asp.net-core-mvc

我非常兴奋能够开始在我的 Mac 上开发 .NET,但在试图弄清楚这一切时却感到沮丧。因此,我通过调用 yo aspnet 创建了一个 WebApplication,并且开箱即用,效果很好。它带有与项目中存储的本地数据库的连接。我遇到问题的地方是将其连接到我的 Azure 门户中托管的远程数据库。

下面的我的连接字符串直接来 self 的 azure 门户。我已将 appsettings.json“DefaultConnection”属性更新为该值(下面缺少用户名和密码),但收到类似“ArgumentException:不支持关键字:'服务器'”之类的错误。我尝试了几种不同的连接字符串,但没有一个有效。

诚然,我对这一切都很陌生,所以我可能错过了一些简单的东西,但在网上搜索时我还没有找到解决方案。

Server=tcp:mydbserver.database.windows.net,1433;Initial Catalog=LH;Persist Security Info=False;User ID={your_username};Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;

这里是我的整个appsettings.json(没有用户名和密码...)供引用

{
  "ConnectionStrings": {
    //"DefaultConnection": "Data Source=LH.db"
    "DefaultConnection": "Server=tcp:mydbserver.database.windows.net,1433;Initial Catalog=lighthouseFSQ;Persist Security Info=False;User ID={Username};Password={Password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"        
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

非常感谢任何帮助。仅供引用,我确实在 Windows VS2015 中尝试过此操作,效果很好。

最佳答案

默认情况下,dotnet new -t web 模板使用 SQLite 数据库,因此仅更改连接字符串不足以更改提供程序。

您还需要从 project.json 中删除 Microsoft.EntityFrameworkCore.Sqlite 包,并将其替换为 Microsoft.EntityFramework.SqlServer (假设您使用的是 Azure 的 SQLServer)。然后在您的 Startup.cs 中您需要替换

// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));

// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

并在必要时更改 namespace 。

更新

在project.json中,您只需更改Sqlite的依赖关系。

"dependencies": {
  ...
  "Microsoft.EntityFrameworkCore.Sqlite": "1.0.1",
  ...
  }
}

"dependencies": {
  ...
  "Microsoft.EntityFrameworkCore.SqlServer": "1.0.1",
  ...
  }
}

如果还有一个 Microsoft.EntityFrameworkCore.Sqlite.Design 也将其更改为 Microsoft.EntityFrameworkCore.SqlServer.Design,那么它就用于脚手架等。

关于azure - 如何使用标准 dotnet Web 模板连接到 Azure 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40635049/

相关文章:

ios - 如何在iOS中从Azure notificationhub获取registrationId

azure - 在不删除虚拟机的情况下创建 Windows azure 镜像?

asp.net-core - 在 ASP.NET Core 中获取 Action 的绝对路径

c# - DI 到 ASP.NET MVC 6 中的需求/策略

c# - 访问静态类的配置/设置 - Asp Core

azure - 无法看到 Azure 内部负载均衡器中后端池中设置的可用性(SKU 为 "standard")

azure - Azure 应用服务是否提供 TLS 1.3?

c# - 库 NuGet 配置无效

c# - ASP.NET Core JWT 将角色声明映射到 ClaimsIdentity

c# - 查看帖子表单返回null?