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

如何使用C# .NET向Azure Data Explorer表批量导入实体列表

用C#将实体列表导入Azure Data Explorer(ADX)表的实现方案

前提条件

  • 已创建ADX集群、TestDB数据库及Test表(表结构需包含Id(int类型)和Name(string类型)字段)
  • 已定义实现ITableEntity的TestEntity类,并准备好待导入的实体列表:
public class TestEntity : ITableEntity
{ 
    public int Id { get; set; }
    public string Name { get; set; }
    // ITableEntity接口必填属性,无需使用可设默认值
    public string PartitionKey { get; set; }
    public string RowKey { get; set; }
    public DateTimeOffset? Timestamp { get; set; }
    public ETag ETag { get; set; }
}

List<TestEntity> entities = new List<TestEntity>();
entities.Add(new TestEntity{ Id = 1, Name = "Test1" });
entities.Add(new TestEntity{ Id = 2, Name = "Test2" });

实现步骤

1. 安装NuGet依赖包

需要安装ADX官方数据摄入相关包:

Install-Package Microsoft.Azure.Kusto.Ingest
Install-Package Microsoft.Azure.Kusto.Data

2. 编写导入代码

使用ADX摄入客户端将实体列表转换为JSON格式后导入,示例代码如下:

using Microsoft.Azure.Kusto.Ingest;
using Newtonsoft.Json;
using System.Linq;
using System.Threading.Tasks;

public async Task ImportEntitiesToAdx()
{
    // ADX集群配置信息
    string clusterUri = "https://<你的ADX集群名>.kusto.windows.net";
    string databaseName = "TestDB";
    string tableName = "Test";
    
    // 认证方式:示例用交互式用户认证,生产环境建议用服务主体认证
    var kustoConnStrBuilder = new KustoConnectionStringBuilder(clusterUri)
        .WithAadUserPromptAuthentication();

    // 创建队列式摄入客户端(适合批量导入场景)
    using (var ingestClient = KustoIngestFactory.CreateQueuedIngestClient(kustoConnStrBuilder))
    {
        // 仅提取需要导入的字段,转换为JSON数组
        var jsonPayload = JsonConvert.SerializeObject(entities.Select(e => new { e.Id, e.Name }));
        
        // 配置摄入属性
        var ingestProperties = new KustoIngestionProperties(databaseName, tableName)
        {
            Format = DataSourceFormat.Json,
            IgnoreFirstRecord = false,
            // 若实体与表字段不匹配,可指定提前创建的ADX数据映射名称
            MappingReference = null
        };

        // 提交摄入任务
        var ingestResult = await ingestClient.IngestFromStringAsync(jsonPayload, ingestProperties);
        
        // 验证导入状态(可选)
        var status = await ingestResult.GetIngestionStatusAsync();
        if (status.Status == IngestionStatus.Succeeded)
        {
            // 导入成功后的业务逻辑
        }
    }
}

3. 关键补充说明

  • 生产环境认证:替换为服务主体认证更安全,配置示例:
    .WithAadApplicationKeyAuthentication(
        clientId: "<你的应用客户端ID>",
        clientSecret: "<应用密钥>",
        authority: "<租户ID>"
    )
    
  • 数据格式可选:除JSON外,也可转换为CSV格式导入,只需修改Format为DataSourceFormat.Csv并生成对应CSV字符串。
  • 字段映射:若实体字段与ADX表字段名称/类型不一致,可在ADX中创建数据映射,然后在ingestProperties中指定MappingReference。

预期导入结果

导入完成后,TestDB库的Test表将呈现如下数据:

+------+--------+
|  Id  |   Name |
+------+--------+
| 1    | Test1  |
| 2    | Test2  |
+------+--------+

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 18:45:42