我们有一个 Azure 专用 SQL 池。我们希望利用 ADO.NET(SqlConnection 和 SqlCommand)从 Azure 应用服务(.NET Core 8 C#)连接到它。
实现此功能需要采取哪些步骤?我们是否需要将应用服务的托管标识添加到 SQL 池中?
我尝试通过我的
Dedicated pool
、Asp.net
Web 应用程序访问 Azure Synapse .Net 6.0
,它运行成功:-
In Services Folder >
ProductService.cs:-
using sqlapp.Models;
using System.Data.SqlClient;
namespace sqlapp.Services
{
public class ProductService : IProductService
{
private readonly IConfiguration _configuration;
public ProductService(IConfiguration configuration)
{
_configuration = configuration;
}
private SqlConnection GetConnection()
{
return new SqlConnection(_configuration.GetConnectionString("SQLConnection"));
}
public List<Product> GetProducts()
{
List<Product> _product_lst = new List<Product>();
string _statement = "SELECT ProductID,ProductName,Quantity from Products";
SqlConnection _connection = GetConnection();
_connection.Open();
SqlCommand _sqlcommand = new SqlCommand(_statement, _connection);
using (SqlDataReader _reader = _sqlcommand.ExecuteReader())
{
while (_reader.Read())
{
Product _product = new Product()
{
ProductID = _reader.GetInt32(0),
ProductName = _reader.GetString(1),
Quantity = _reader.GetInt32(2)
};
_product_lst.Add(_product);
}
}
_connection.Close();
return _product_lst;
}
}
}
In Pages Folder > Index.cshtml:-
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
<div class="text-center">
<h1 class="display-4">This is a list of Products</h1>
<table class="table table-bordered">
<thead>
<tr>
<th scope="col">Product ID</th>
<th scope="col">Product Name</th>
<th scope="col">Quantity</th>
</tr>
</thead>
<tbody>
@foreach(var product in Model.Products)
{
<tr>
<th scope="row">@product.ProductID</th>
<td>@product.ProductName</td>
<td>@product.Quantity</td>
</tr>
}
</tbody>
</table>
</div>
Azure synapse 专用池 ado.net 连接字符串,参考:-
Name: SQLConnection
Value: Server=tcp:xxxorkspace45.sql.azuresynapse.net,1433;Initial Catalog=pooldb;Persist Security Info=False;User ID=xxxxxser;Password=Wxxxxxx;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
在Web应用程序的连接字符串中添加以下设置:-
Azure Synapse 网络设置,允许从所有 Azure 服务进行访问:-
输出:-