選項
首頁首頁 Skill 開發營運和 CI/CD azure-resource-manager-sql-dotnet

azure-resource-manager-sql-dotnet

microsoft/skills microsoft/skills

使用 .NET 版 Azure Resource Manager SDK 來管理 Azure SQL 資源(伺服器、資料庫、彈性資料庫池、防火牆規則、故障轉移群組)。

...展開全部
2
更新時間 2026-09-18

Azure.ResourceManager.Sql (.NET)

用於透過 Azure Resource Manager 配置及管理 Azure SQL 資源的管理平面 SDK。

⚠️ 管理層與資料層的區別

  • 此 SDK (Azure.ResourceManager.Sql):建立伺服器、資料庫、彈性彙集、設定防火牆規則、管理故障轉移群組
  • 資料層 SDK (Microsoft.Data.SqlClient):執行查詢、儲存程序、管理連線

安裝

dotnet add package Azure.ResourceManager.Sql
dotnet add package Azure.Identity

當前版本:穩定版 v1.3.0、預覽版 v1.4.0-beta.3

環境變數

AZURE_SUBSCRIPTION_ID= # 必填:Azure 訂閱 ID
AZURE_TOKEN_CREDENTIALS=prod  # 僅當在生產環境中使用 DefaultAzureCredential 時才必填
AZURE_TENANT_ID= # 用於服務主體驗證(可選)
AZURE_CLIENT_ID= # 用於服務主體驗證(可選)
AZURE_CLIENT_SECRET= # 用於服務主體驗證(可選)

驗證

using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Sql;

// 本地開發環境:使用 DefaultAzureCredential。生產環境:請將 AZURE_TOKEN_CREDENTIALS 設定為 prod 或 AZURE_TOKEN_CREDENTIALS=
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// 或者在生產環境中直接使用特定憑證:
// 參閱 https://learn.microsoft.com/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#credential-classes
// var credential = new ManagedIdentityCredential();
var armClient = new ArmClient(credential);

// 取得訂閱
var subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");
var subscription = armClient.GetSubscriptionResource(
    new ResourceIdentifier($"/subscriptions/{subscriptionId}"));

資源層級結構

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

核心工作流程

1. 建立 SQL Server

using Azure.ResourceManager.Sql;
using Azure.ResourceManager.Sql.Models;

// 取得資源群組
var resourceGroup = await subscription
    .GetResourceGroupAsync("my-resource-group");

// 定義伺服器
var serverData = new SqlServerData(AzureLocation.EastUS)
{
    AdministratorLogin = "sqladmin",
    AdministratorLoginPassword = "YourSecurePassword123!",
    Version = "12.0",
    MinimalTlsVersion = SqlMinimalTlsVersion.Tls1_2,
    PublicNetworkAccess = ServerNetworkAccessFlag.Enabled
};

// 建立伺服器(長期執行操作)
var serverCollection = resourceGroup.Value.GetSqlServers();
var operation = await serverCollection.CreateOrUpdateAsync(
    WaitUntil.Completed,
    "my-sql-server",
    serverData);

SqlServerResource server = operation.Value;

2. 建立 SQL 資料庫

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. 建立彈性資料庫池

var poolData = new ElasticPoolData(AzureLocation.EastUS)
{
    Sku = new SqlSku("StandardPool")
    {
        Tier = "Standard",
        Capacity = 100 // 100 eDTU
    },
    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. 將資料庫新增至彈性資料庫池

var databaseData = new SqlDatabaseData(AzureLocation.EastUS)
{
    ElasticPoolId = pool.Id
};

await databaseCollection.CreateOrUpdateAsync(
    WaitUntil.Completed,
    "pooled-database",
    databaseData);

5. 設定防火牆規則

// 允許 Azure 服務存取
var azureServicesRule = new SqlFirewallRuleData
{
    StartIPAddress = "0.0.0.0",
    EndIPAddress = "0.0.0.0"
};

var firewallCollection = server.GetSqlFirewallRules();
await firewallCollection.CreateOrUpdateAsync(
    WaitUntil.Completed,
    "AllowAzureServices",
    azureServicesRule);

// 允許特定 IP 範圍
var clientRule = new SqlFirewallRuleData
{
    StartIPAddress = "203.0.113.0",
    EndIPAddress = "203.0.113.255"
};

await firewallCollection.CreateOrUpdateAsync(
    WaitUntil.Completed,
    "AllowClientIPs",
    clientRule);

6. 列出資源

// 列出訂閱中的所有伺服器
await foreach (var srv in subscription.GetSqlServersAsync())
{
    Console.WriteLine($"伺服器:{srv.Data.Name} 位於 {srv.Data.Location}");
}

// 列出伺服器中的資料庫
await foreach (var db in server.GetSqlDatabases())
{
    Console.WriteLine($"資料庫:{db.Data.Name},SKU:{db.Data.Sku?.Name}");
}

// 列出彈性資料庫群組
await foreach (var ep in server.GetElasticPools())
{
    Console.WriteLine($"資料庫群組:{ep.Data.Name},DTU:{ep.Data.Sku?.Capacity}");
}

7. 取得連線字串

// 建立連線字串(伺服器 FQDN 可預測)
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=;" +
    "MultipleActiveResultSets=False;" +
    "Encrypt=True;" +
    "TrustServerCertificate=False;" +
    "Connection Timeout=30;";

金鑰類型參考

類型 用途
ArmClient 所有 ARM 操作的入口點
SqlServerResource 代表一個 Azure SQL 伺服器
SqlServerCollection 用於伺服器 CRUD 操作的集合
SqlDatabaseResource 代表一個 SQL 資料庫
SqlDatabaseCollection 用於資料庫 CRUD 的集合
ElasticPoolResource 代表一個彈性資料庫池
ElasticPoolCollection 用於彈性池 CRUD 的集合
SqlFirewallRuleResource 代表一則防火牆規則
SqlFirewallRuleCollection 用於防火牆規則 CRUD 的集合
SqlServerData 伺服器建立/更新資料包
SqlDatabaseData 資料庫建立/更新載荷
ElasticPoolData 彈性彙集建立/更新載荷
SqlFirewallRuleData 防火牆規則建立/更新有效載荷
SqlSku SKU 配置(層級、容量)

常見 SKU

資料庫 SKU

SKU 名稱 層級 說明
基本 基本 5 個 DTU,最多 2 GB
S0-S12 標準 10–3000 DTU
P1-P15 高級 125-4000 DTU
GP_Gen5_2 通用型 基於 vCore,2 個 vCore
BC_Gen5_2 業務關鍵型 基於 vCore,2 個 vCore
HS_Gen5_2 超大規模 基於 vCore,2 個 vCore

彈性資源池 SKU

SKU 名稱 層級 說明
BasicPool 基本 50–1600 eDTU
標準資源池 標準 50–3000 eDTU
尊享池 尊榮 125–4000 eDTU
GP_Gen5_2 GeneralPurpose 基於 vCore
BC_Gen5_2 業務關鍵 基於 vCore

最佳實務

  1. 對於必須在繼續執行前完成的操作,請使用WaitUntil.Completed
  2. 若需手動輪詢或並行執行操作 請使用WaitUntil.Started
  3. 請始終使用DefaultAzureCredential— 切勿在生產環境中將密碼硬編碼
  4. 針對 ARM API 錯誤處理RequestFailedException
  5. 對於幺正操作,請使用CreateOrUpdateAsync
  6. 透過Get*方法瀏覽層級結構(例如:server.GetSqlDatabases()
  7. 管理多個資料庫時,請使用彈性資料庫池以進行成本優化
  8. 嘗試連線前請先設定防火牆規則

錯誤處理

using Azure;

try
{
    var operation = await serverCollection.CreateOrUpdateAsync(
        WaitUntil.Completed, serverName, serverData);
}
catch (RequestFailedException ex) when (ex.Status == 409)
{
    Console.WriteLine("伺服器已存在");
}
catch (RequestFailedException ex) when (ex.Status == 400)
{
    Console.WriteLine($"無效請求:{ex.Message}");
}
catch (RequestFailedException ex)
{
    Console.WriteLine($"ARM 錯誤:{ex.Status} - {ex.ErrorCode}:{ex.Message}");
}

參考檔案

檔案 何時閱讀
references/server-management.md 伺服器 CRUD、管理員憑證、Azure AD 驗證、網路設定
references/database-operations.md 資料庫 CRUD、擴展、備份、還原、複製
references/elastic-pools.md 資料庫彙集管理、新增/移除資料庫、擴展

相關 SDK

SDK 用途 安裝
Microsoft.Data.SqlClient 資料層(執行查詢、儲存程序) dotnet add package Microsoft.Data.SqlClient
Azure.ResourceManager.Sql 管理層(此 SDK) dotnet add package Azure.ResourceManager.Sql
Microsoft.EntityFrameworkCore.SqlServer SQL Server 的 ORM dotnet add package Microsoft.EntityFrameworkCore.SqlServer
在 GitHub 上查看
---
name: azure-resource-manager-sql-dotnet
description: Manage Azure SQL resources (servers, databases, elastic pools, firewall rules, failover groups) using the Azure Resource Manager SDK for .NET.
license: MIT
---

# 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.Sql
dotnet 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 ID
AZURE_TOKEN_CREDENTIALS=prod  # Required only if DefaultAzureCredential is used in production
AZURE_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 subscription
var 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 group
var resourceGroup = await subscription
    .GetResourceGroupAsync("my-resource-group");

// Define server
var 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 services
var 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 range
var 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 subscription
await foreach (var srv in subscription.GetSqlServersAsync())
{
    Console.WriteLine($"Server: {srv.Data.Name} in {srv.Data.Location}");
}

// List databases in a server
await foreach (var db in server.GetSqlDatabases())
{
    Console.WriteLine($"Database: {db.Data.Name}, SKU: {db.Data.Sku?.Name}");
}

// List elastic pools
await 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

| Type | Purpose |
|------|---------|
| `ArmClient` | Entry point for all ARM operations |
| `SqlServerResource` | Represents an Azure SQL server |
| `SqlServerCollection` | Collection for server CRUD |
| `SqlDatabaseResource` | Represents a SQL database |
| `SqlDatabaseCollection` | Collection for database CRUD |
| `ElasticPoolResource` | Represents an elastic pool |
| `ElasticPoolCollection` | Collection for elastic pool CRUD |
| `SqlFirewallRuleResource` | Represents a firewall rule |
| `SqlFirewallRuleCollection` | Collection for firewall rule CRUD |
| `SqlServerData` | Server creation/update payload |
| `SqlDatabaseData` | Database creation/update payload |
| `ElasticPoolData` | Elastic pool creation/update payload |
| `SqlFirewallRuleData` | Firewall rule creation/update payload |
| `SqlSku` | SKU configuration (tier, capacity) |

## Common SKUs

### Database SKUs

| SKU Name | Tier | Description |
|----------|------|-------------|
| `Basic` | Basic | 5 DTUs, 2 GB max |
| `S0`-`S12` | Standard | 10-3000 DTUs |
| `P1`-`P15` | Premium | 125-4000 DTUs |
| `GP_Gen5_2` | GeneralPurpose | vCore-based, 2 vCores |
| `BC_Gen5_2` | BusinessCritical | vCore-based, 2 vCores |
| `HS_Gen5_2` | Hyperscale | vCore-based, 2 vCores |

### Elastic Pool SKUs

| SKU Name | Tier | Description |
|----------|------|-------------|
| `BasicPool` | Basic | 50-1600 eDTUs |
| `StandardPool` | Standard | 50-3000 eDTUs |
| `PremiumPool` | Premium | 125-4000 eDTUs |
| `GP_Gen5_2` | GeneralPurpose | vCore-based |
| `BC_Gen5_2` | BusinessCritical | vCore-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

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

## Related SDKs

| SDK | Purpose | Install |
|-----|---------|---------|
| `Microsoft.Data.SqlClient` | Data plane (execute queries, stored procedures) | `dotnet add package Microsoft.Data.SqlClient` |
| `Azure.ResourceManager.Sql` | Management plane (this SDK) | `dotnet add package Azure.ResourceManager.Sql` |
| `Microsoft.EntityFrameworkCore.SqlServer` | ORM for SQL Server | `dotnet add package Microsoft.EntityFrameworkCore.SqlServer` |

所有檔案

0 個檔案

安裝 azure-resource-manager-sql-dotnet

請下載並將技能檔案解壓縮至您的 .claude/skills/ 目錄中。

下載 ZIP

複製儲存庫並將技能檔案複製到您的專案中。

git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-dotnet/skills/azure-resource-manager-sql-dotnet # Copy SKILL.md to your .claude/skills/ directory

複製 複製
快速設定: 將技能資料夾複製到 .claude/skills/ Claude 會自動偵測並使用該技能
儲存庫 microsoft/skills

相關技能

Verification &amp; Quality Assurance
更新時間 2026-06-29
base44-cli
更新時間 2026-06-29
klingai-upgrade-migration
更新時間 2026-07-03
Railway CLI Management
更新時間 2026-07-02
OR