如何在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的适配方向:
- 在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}"); }
- 替换命名空间为
Microsoft.Data.SqlClient,代码逻辑无需大幅修改,两者API基本兼容。
说明
Azure Function V4基于.NET 6+运行时,对传统的System.Data.SqlClient支持方式调整,显式引用或迁移到新库都能解决问题,推荐使用Microsoft.Data.SqlClient以获得后续官方支持和更新。
内容的提问来源于stack exchange,提问作者Akshay Kumar

