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

如何使用Azure.ArmClient实现数据库重命名与复制操作?

替换Microsoft.Azure.Management.Fluent为Azure.ResourceManager:SQL数据库重命名与复制实现方案

初始化ArmClient(替代原GetAzureObject)

首先替换旧的IAzure初始化逻辑,改用新版ArmClient:

private ArmClient GetArmClient()
{
    var clientId = _configuration["AzureClientId"];
    var clientSecret = _configuration["AzureClientSecret"];
    var tenantId = _configuration["AzureTenantId"];
    var subscriptionId = _configuration["AzureSubscriptionId"];

    var credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
    return new ArmClient(credential, subscriptionId);
}

一、数据库重命名实现

新版SDK中,数据库重命名需通过RenameAsync方法配合SqlResourceMoveDefinition完成,核心是指定新名称对应的资源ID:

// 假设已获取目标SQL服务器资源(fromServer 为 SqlServerResource)
var targetDbName = toName;
var backupDbName = $"{targetDbName}-Old";

var targetDb = fromServer.GetSqlDatabase(targetDbName);
if (await targetDb.ExistsAsync())
{
    var targetDbResource = await targetDb.GetAsync();
    
    // 构建新名称的数据库资源ID
    var newBackupDbId = SqlDatabaseResource.CreateResourceIdentifier(
        subscriptionId: targetDbResource.Value.Id.SubscriptionId,
        resourceGroupName: targetDbResource.Value.Id.ResourceGroupName,
        serverName: fromServer.Name,
        databaseName: backupDbName);
    
    var moveDefinition = new SqlResourceMoveDefinition
    {
        // 关键:设置目标资源ID,即重命名后的数据库ID
        TargetResourceId = newBackupDbId.ToString()
    };

    _log.LogInformation("Renaming target database from {0} to {1}", targetDbName, backupDbName);
    await targetDbResource.Value.RenameAsync(WaitUntil.Completed, moveDefinition);
}

二、数据库复制实现

数据库复制需通过SqlDatabaseCollection.CreateOrUpdateAsync方法,指定CreateMode为Copy并设置源数据库ID:

// 获取源数据库
var sourceDb = fromServer.GetSqlDatabase(fromName);
if (!await sourceDb.ExistsAsync())
{
    throw new InvalidOperationException("Unable to find original database");
}
var sourceDbResource = await sourceDb.GetAsync();

// 构建复制参数
var copyDbParameters = new SqlDatabaseData(sourceDbResource.Value.Data.Location)
{
    CreateMode = SqlDatabaseCreateMode.Copy,
    // 指定源数据库的资源ID
    SourceDatabaseId = sourceDbResource.Value.Id
};

_log.LogInformation("Copying database from {0} to {1}", fromName, toName);
// 执行复制操作
var copyOperation = await fromServer.GetSqlDatabases().CreateOrUpdateAsync(
    WaitUntil.Completed,
    toName,
    copyDbParameters);

// 返回操作是否成功
return copyOperation.Value != null;

完整的CopyDb方法重写

整合上述逻辑,替换旧版CopyDb方法:

public async Task<bool> CopyDb(string? server, string? fromName, string? toName)
{
    _log.LogInformation("Connecting to Azure");
    var armClient = GetArmClient();

    // 获取默认订阅
    var subscription = await armClient.GetDefaultSubscriptionAsync();

    // 查找目标SQL服务器
    var sqlServers = subscription.GetSqlServers();
    var fromServer = await sqlServers.FirstOrDefaultAsync(s => server != null && s.Name.Contains(server));
    if (fromServer == null)
    {
        throw new InvalidOperationException("Unable to find original database server");
    }

    var toNameBackup = $"{toName}-Old";
    var sqlDatabases = fromServer.GetSqlDatabases();

    // 校验源数据库存在性
    var sourceDb = sqlDatabases.Get(fromName);
    if (!await sourceDb.ExistsAsync())
    {
        throw new InvalidOperationException("Unable to find original database");
    }

    // 删除已存在的备份数据库(仅当目标数据库也存在时)
    var backupDb = sqlDatabases.Get(toNameBackup);
    var targetDb = sqlDatabases.Get(toName);
    if (await backupDb.ExistsAsync() && await targetDb.ExistsAsync())
    {
        _log.LogInformation("Deleting any existing backup called {0}", toNameBackup);
        await backupDb.DeleteAsync(WaitUntil.Completed);
    }

    // 重命名目标数据库到备份名称
    if (await targetDb.ExistsAsync())
    {
        var targetDbResource = await targetDb.GetAsync();
        var newBackupDbId = SqlDatabaseResource.CreateResourceIdentifier(
            subscription.Id.SubscriptionId,
            fromServer.Id.ResourceGroupName,
            fromServer.Name,
            toNameBackup);

        var moveDefinition = new SqlResourceMoveDefinition
        {
            TargetResourceId = newBackupDbId.ToString()
        };

        _log.LogInformation("Renaming target database from {0} to {1}", toName, toNameBackup);
        await targetDbResource.Value.RenameAsync(WaitUntil.Completed, moveDefinition);
    }

    // 执行数据库复制
    var sourceDbResource = await sourceDb.GetAsync();
    var copyDbData = new SqlDatabaseData(sourceDbResource.Value.Data.Location)
    {
        CreateMode = SqlDatabaseCreateMode.Copy,
        SourceDatabaseId = sourceDbResource.Value.Id
    };

    _log.LogInformation("Copying database from {0} to {1}", fromName, toName);
    var copyResult = await sqlDatabases.CreateOrUpdateAsync(WaitUntil.Completed, toName, copyDbData);

    return copyResult.Value != null;
}

内容的提问来源于stack exchange,提问作者Max Power

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 17:55:42