Azure Resource Manager Sql Dotnet

作者 microsoft354361d83247MIT收錄於 2026年10月8日更新於 2026年10月8日

Azure Resource Manager SDK for Azure SQL in .NET. Use for MANAGEMENT PLANE operations: creating/managing SQL servers, databases, elastic pools, firewall rules, and failover groups via Azure Resource Manager. NOT for data plane operations (executing queries) - use Microsoft.Data.SqlClient for that. Triggers: "SQL server", "create SQL database", "manage SQL resources", "ARM SQL", "SqlServerResource", "provision Azure SQL", "elastic pool", "firewall rule".

精選僅含說明DevOps & Cloud
AI 產生的概覽

指導在 .NET 中透過 Azure Resource Manager 管理平面佈建 Azure SQL 伺服器、資料庫、彈性集區、防火牆規則與容錯移轉群組。

功能
此技能說明用於 Azure SQL 管理平面操作的 Azure.ResourceManager.Sql .NET SDK。內容涵蓋建立與管理 SQL 伺服器、資料庫、彈性集區、防火牆規則及容錯移轉群組,列出資源、建構連接字串以及處理 ARM 錯誤,並附有 SKU 表與最佳實務說明。它也指向伺服器管理、資料庫操作與彈性集區三個參考檔案。技能明確排除資料平面的查詢執行,並將其歸入 Microsoft.Data.SqlClient。
適用情境
適用於在 .NET 中透過 Azure Resource Manager 佈建或管理 Azure SQL 資源的情境,例如建立 SQL 伺服器、資料庫或彈性集區、設定防火牆規則,或調整規模與列出 SQL 資源。它不用於對資料庫執行查詢或預存程序。
執行需求
需要 .NET SDK 以及 Azure.ResourceManager.Sql 和 Azure.Identity NuGet 套件、一個 Azure 訂用帳戶和相應認證(DefaultAzureCredential,或透過 AZURE_SUBSCRIPTION_ID、AZURE_TENANT_ID、AZURE_CLIENT_ID 與 AZURE_CLIENT_SECRET 使用服務主體)。需要連線至 Azure Resource Manager 的網路存取。不隨附指令碼,僅有指示與三個參考 Markdown 檔案。

Azure.ResourceManager.Sql (.NET)

Management plane SDK for provisioning and managing Azure SQL resources via Azure Resource Manager.

⚠️ Management vs Data Plane

  • This SDK (Azure.ResourceManager.Sql): Create servers, databases, elastic pools, configure firewall rules, manage failover groups
  • Data Plane SDK (Microsoft.Data.SqlClient): Execute queries, stored procedures, manage connections

Installation

bash
dotnet add package Azure.ResourceManager.Sqldotnet add package Azure.Identity

Current Versions: Stable v1.3.0, Preview v1.4.0-beta.3

Environment Variables

bash
AZURE_SUBSCRIPTION_ID=<your-subscription-id>  # Required: Azure subscription IDAZURE_TOKEN_CREDENTIALS=prod  # Required only if DefaultAzureCredential is used in productionAZURE_TENANT_ID=<tenant-id>  # For service principal auth (optional)AZURE_CLIENT_ID=<client-id>  # For service principal auth (optional)AZURE_CLIENT_SECRET=<client-secret>  # For service principal auth (optional)

Authentication

csharp
using Azure.Identity;using Azure.ResourceManager;using Azure.ResourceManager.Sql;
// Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>var credential = new DefaultAzureCredential(    DefaultAzureCredential.DefaultEnvironmentVariableName);// Or use a specific credential directly in production:// See https://learn.microsoft.com/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#credential-classes// var credential = new ManagedIdentityCredential();var armClient = new ArmClient(credential);
// Get subscriptionvar subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");var subscription = armClient.GetSubscriptionResource(    new ResourceIdentifier($"/subscriptions/{subscriptionId}"));

Resource Hierarchy

ArmClient└── SubscriptionResource    └── ResourceGroupResource        └── SqlServerResource            ├── SqlDatabaseResource            ├── ElasticPoolResource            │   └── ElasticPoolDatabaseResource            ├── SqlFirewallRuleResource            ├── FailoverGroupResource            ├── ServerBlobAuditingPolicyResource            ├── EncryptionProtectorResource            └── VirtualNetworkRuleResource

Core Workflow

1. Create SQL Server

csharp
using Azure.ResourceManager.Sql;using Azure.ResourceManager.Sql.Models;
// Get resource groupvar resourceGroup = await subscription    .GetResourceGroupAsync("my-resource-group");
// Define servervar serverData = new SqlServerData(AzureLocation.EastUS){    AdministratorLogin = "sqladmin",    AdministratorLoginPassword = "YourSecurePassword123!",    Version = "12.0",    MinimalTlsVersion = SqlMinimalTlsVersion.Tls1_2,    PublicNetworkAccess = ServerNetworkAccessFlag.Enabled};
// Create server (long-running operation)var serverCollection = resourceGroup.Value.GetSqlServers();var operation = await serverCollection.CreateOrUpdateAsync(    WaitUntil.Completed,    "my-sql-server",    serverData);
SqlServerResource server = operation.Value;

2. Create SQL Database

csharp
var databaseData = new SqlDatabaseData(AzureLocation.EastUS){    Sku = new SqlSku("S0") { Tier = "Standard" },    MaxSizeBytes = 2L * 1024 * 1024 * 1024, // 2 GB    Collation = "SQL_Latin1_General_CP1_CI_AS",    RequestedBackupStorageRedundancy = SqlBackupStorageRedundancy.Local};
var databaseCollection = server.GetSqlDatabases();var dbOperation = await databaseCollection.CreateOrUpdateAsync(    WaitUntil.Completed,    "my-database",    databaseData);
SqlDatabaseResource database = dbOperation.Value;

3. Create Elastic Pool

csharp
var poolData = new ElasticPoolData(AzureLocation.EastUS){    Sku = new SqlSku("StandardPool")    {        Tier = "Standard",        Capacity = 100 // 100 eDTUs    },    PerDatabaseSettings = new ElasticPoolPerDatabaseSettings    {        MinCapacity = 0,        MaxCapacity = 100    }};
var poolCollection = server.GetElasticPools();var poolOperation = await poolCollection.CreateOrUpdateAsync(    WaitUntil.Completed,    "my-elastic-pool",    poolData);
ElasticPoolResource pool = poolOperation.Value;

4. Add Database to Elastic Pool

csharp
var databaseData = new SqlDatabaseData(AzureLocation.EastUS){    ElasticPoolId = pool.Id};
await databaseCollection.CreateOrUpdateAsync(    WaitUntil.Completed,    "pooled-database",    databaseData);

5. Configure Firewall Rules

csharp
// Allow Azure servicesvar azureServicesRule = new SqlFirewallRuleData{    StartIPAddress = "0.0.0.0",    EndIPAddress = "0.0.0.0"};
var firewallCollection = server.GetSqlFirewallRules();await firewallCollection.CreateOrUpdateAsync(    WaitUntil.Completed,    "AllowAzureServices",    azureServicesRule);
// Allow specific IP rangevar clientRule = new SqlFirewallRuleData{    StartIPAddress = "203.0.113.0",    EndIPAddress = "203.0.113.255"};
await firewallCollection.CreateOrUpdateAsync(    WaitUntil.Completed,    "AllowClientIPs",    clientRule);

6. List Resources

csharp
// List all servers in subscriptionawait foreach (var srv in subscription.GetSqlServersAsync()){    Console.WriteLine($"Server: {srv.Data.Name} in {srv.Data.Location}");}
// List databases in a serverawait foreach (var db in server.GetSqlDatabases()){    Console.WriteLine($"Database: {db.Data.Name}, SKU: {db.Data.Sku?.Name}");}
// List elastic poolsawait foreach (var ep in server.GetElasticPools()){    Console.WriteLine($"Pool: {ep.Data.Name}, DTU: {ep.Data.Sku?.Capacity}");}

7. Get Connection String

csharp
// Build connection string (server FQDN is predictable)var serverFqdn = $"{server.Data.Name}.database.windows.net";var connectionString = $"Server=tcp:{serverFqdn},1433;" +    $"Initial Catalog={database.Data.Name};" +    "Persist Security Info=False;" +    $"User ID={server.Data.AdministratorLogin};" +    "Password=<your-password>;" +    "MultipleActiveResultSets=False;" +    "Encrypt=True;" +    "TrustServerCertificate=False;" +    "Connection Timeout=30;";

Key Types Reference

TypePurpose
ArmClientEntry point for all ARM operations
SqlServerResourceRepresents an Azure SQL server
SqlServerCollectionCollection for server CRUD
SqlDatabaseResourceRepresents a SQL database
SqlDatabaseCollectionCollection for database CRUD
ElasticPoolResourceRepresents an elastic pool
ElasticPoolCollectionCollection for elastic pool CRUD
SqlFirewallRuleResourceRepresents a firewall rule
SqlFirewallRuleCollectionCollection for firewall rule CRUD
SqlServerDataServer creation/update payload
SqlDatabaseDataDatabase creation/update payload
ElasticPoolDataElastic pool creation/update payload
SqlFirewallRuleDataFirewall rule creation/update payload
SqlSkuSKU configuration (tier, capacity)

Common SKUs

Database SKUs

SKU NameTierDescription
BasicBasic5 DTUs, 2 GB max
S0-S12Standard10-3000 DTUs
P1-P15Premium125-4000 DTUs
GP_Gen5_2GeneralPurposevCore-based, 2 vCores
BC_Gen5_2BusinessCriticalvCore-based, 2 vCores
HS_Gen5_2HyperscalevCore-based, 2 vCores

Elastic Pool SKUs

SKU NameTierDescription
BasicPoolBasic50-1600 eDTUs
StandardPoolStandard50-3000 eDTUs
PremiumPoolPremium125-4000 eDTUs
GP_Gen5_2GeneralPurposevCore-based
BC_Gen5_2BusinessCriticalvCore-based

Best Practices

  1. Use WaitUntil.Completed for operations that must finish before proceeding
  2. Use WaitUntil.Started when you want to poll manually or run operations in parallel
  3. Always use DefaultAzureCredential — never hardcode passwords in production
  4. Handle RequestFailedException for ARM API errors
  5. Use CreateOrUpdateAsync for idempotent operations
  6. Navigate hierarchy via Get* methods (e.g., server.GetSqlDatabases())
  7. Use elastic pools for cost optimization when managing multiple databases
  8. Configure firewall rules before attempting connections

Error Handling

csharp
using Azure;
try{    var operation = await serverCollection.CreateOrUpdateAsync(        WaitUntil.Completed, serverName, serverData);}catch (RequestFailedException ex) when (ex.Status == 409){    Console.WriteLine("Server already exists");}catch (RequestFailedException ex) when (ex.Status == 400){    Console.WriteLine($"Invalid request: {ex.Message}");}catch (RequestFailedException ex){    Console.WriteLine($"ARM Error: {ex.Status} - {ex.ErrorCode}: {ex.Message}");}

Reference Files

FileWhen to Read
references/server-management.md [blocked]Server CRUD, admin credentials, Azure AD auth, networking
references/database-operations.md [blocked]Database CRUD, scaling, backup, restore, copy
references/elastic-pools.md [blocked]Pool management, adding/removing databases, scaling

Related SDKs

SDKPurposeInstall
Microsoft.Data.SqlClientData plane (execute queries, stored procedures)dotnet add package Microsoft.Data.SqlClient
Azure.ResourceManager.SqlManagement plane (this SDK)dotnet add package Azure.ResourceManager.Sql
Microsoft.EntityFrameworkCore.SqlServerORM for SQL Serverdotnet add package Microsoft.EntityFrameworkCore.SqlServer

來源與署名

來源:microsoft/skills位於.github/plugins/azure-sdk-dotnet/skills/azure-resource-manager-sql-dotnet提交354361d

授權條款: MIT

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架