You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Azure SDK for .NET导入.bacpac并移入Azure弹性池?

问题解答

可以通过新版Azure SDK for .NET在完成.bacpac导入后,将数据库移入Azure弹性池。核心逻辑是先完成数据库导入操作,再通过更新数据库配置,绑定目标弹性池的资源ID实现迁移。

修改后的完整代码

public static void RestoreToElasticPool(string sourceDbName, string bacpacFileName, string targetElasticPoolName)
{
    string backupName = sourceDbName + "/dbbackups/" + bacpacFileName;
    string targetDbName = sourceDbName; // 可根据需求自定义目标数据库名称

    // 初始化ArmClient
    Azure.ResourceManager.ArmClient armClient = new(new DefaultAzureCredential());

    // 获取目标SQL Server资源
    Azure.Core.ResourceIdentifier sqlServerId = SqlServerResource.CreateResourceIdentifier(
        _ResourceGroupSubscriptionId,
        _ResourceGroupName,
        _SqlServerName);
    Azure.ResourceManager.Sql.SqlServerResource sqlServerResource = armClient.GetSqlServerResource(sqlServerId);

    // 定位存储中的Bacpac文件
    BlobServiceClient bSvcCl = GetStorageAccount(_StorageConnectionString);
    BlobContainerClient contCl = bSvcCl.GetBlobContainerClient(_ActiveProjectsContainer);
    BlockBlobClient blockBlobClient = contCl.GetBlockBlobClient(backupName);

    // 获取存储账户访问密钥
    Azure.ResourceManager.Storage.Models.StorageAccountKey storageAccountKey = GetStorageAccountKey(armClient);
    StorageKeyType storageKeyType = StorageKeyType.StorageAccessKey;

    // 构建导入配置
    Azure.ResourceManager.Sql.Models.DatabaseImportDefinition importDefinition = new(
        storageKeyType,
        storageAccountKey.Value,
        blockBlobClient.Uri,
        _SqlUserName,
        _SqlSvrPwd)
    {
        DatabaseName = targetDbName // 明确指定导入后的数据库名称
    };

    // 执行导入并等待完成
    var importOperation = sqlServerResource.ImportDatabase(Azure.WaitUntil.Completed, importDefinition);
    SqlDatabaseResource importedDb = importOperation.Value;

    // 获取目标弹性池资源
    Azure.Core.ResourceIdentifier elasticPoolId = ElasticPoolResource.CreateResourceIdentifier(
        _ResourceGroupSubscriptionId,
        _ResourceGroupName,
        _SqlServerName,
        targetElasticPoolName);
    ElasticPoolResource targetElasticPool = armClient.GetElasticPoolResource(elasticPoolId);

    // 构建数据库更新参数,绑定弹性池
    SqlDatabasePatch patch = new()
    {
        ElasticPoolId = targetElasticPool.Id
    };

    // 执行更新,将数据库移入弹性池
    importedDb.Update(Azure.WaitUntil.Completed, patch);
}

关键操作说明

  • 导入阶段:保留原有导入逻辑,补充DatabaseName参数,确保后续能精准定位到刚导入的数据库资源。
  • 弹性池定位:通过弹性池的资源ID获取目标池实例,需提前确认该弹性池已存在于目标SQL Server中。
  • 数据库更新:使用SqlDatabasePatch设置ElasticPoolId,调用Update方法完成迁移,此操作会将数据库从独立计算层切换至弹性池。

注意事项

  • 执行代码的身份需具备SQL Server参与者和弹性池参与者权限,避免因权限不足导致操作失败。
  • 导入的数据库服务层级需与目标弹性池兼容(例如弹性池为GP层级,导入数据库不能是BC层级)。
  • 迁移过程中数据库会有短暂不可用,建议在业务低峰期执行。

内容的提问来源于stack exchange,提问作者E. A. Bagby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 15:40:56