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

如何在Azure Function V4门户中使用System.Data.SqlClient命名空间

Azure Function V4 中使用 System.Data.SqlClient 的解决方法

问题场景

在Azure门户的Azure Function V4中运行以下C#脚本时出现错误:

using System.Data.SqlClient;
using System;

public static void Run(TimerInfo myTimer, ILogger log)
{
    var conn = new SqlConnection("MyConnectionString");
    log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
}

报错信息:

run.csx(7,20): error CS1069: The type name 'SqlConnection' could not be found in the namespace 'System.Data.SqlClient'. This type has been forwarded to assembly 'System.Data.SqlClient, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' Consider adding a reference to that assembly

该代码在VS Code开发环境及Azure Function V3版本中可正常运行,升级至V4后出现上述问题。

解决方法

方法1:添加程序集引用指令

在run.csx文件开头添加程序集引用,明确引入System.Data.SqlClient:

#r "System.Data.SqlClient"
using System.Data.SqlClient;
using System;

public static void Run(TimerInfo myTimer, ILogger log)
{
    var conn = new SqlConnection("MyConnectionString");
    log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
}

Azure Function V4默认不再自动引用该程序集,需要显式声明。

方法2:迁移到Microsoft.Data.SqlClient(推荐)

System.Data.SqlClient已被标记为弃用,官方推荐使用Microsoft.Data.SqlClient替代,这也是Azure Function V4的适配方向:

  1. 在run.csx开头添加NuGet包引用:
#r "nuget: Microsoft.Data.SqlClient, 5.1.5"
using Microsoft.Data.SqlClient;
using System;

public static void Run(TimerInfo myTimer, ILogger log)
{
    var conn = new SqlConnection("MyConnectionString");
    log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
}
  1. 替换命名空间为Microsoft.Data.SqlClient,代码逻辑无需大幅修改,两者API基本兼容。

说明

Azure Function V4基于.NET 6+运行时,对传统的System.Data.SqlClient支持方式调整,显式引用或迁移到新库都能解决问题,推荐使用Microsoft.Data.SqlClient以获得后续官方支持和更新。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 10:30:43