.NET7调用SQL Server存储过程时DateOnly类型映射失败问题
解决.NET 7中DateOnly到Azure SQL date类型的映射错误
问题描述
调用Azure SQL存储过程时,传入System.DateOnly参数触发以下错误:
No mapping exists from object type System.DateOnly to a known managed provider native type.
相关代码如下:
存储过程定义:
CREATE PROCEDURE [dbo].[sproc_WMSSummaryStats] @userId INT, @datefrom date, @dateto date AS .....
Web API端点:
[HttpGet("homePageSummaryData")] public string homePageSummaryData(int user, int warehouseId, int zoneId, DateOnly startDate, DateOnly endDate, string licenseKey) { // .... }
存储过程调用代码:
cmd.Connection = conn; conn.Open(); cmd.Parameters.AddWithValue("@userID", user); cmd.Parameters.AddWithValue("@datefrom" , startDate); cmd.Parameters.AddWithValue("@dateto", endDate);
解决方案
方案1:手动指定SQL参数类型
避免AddWithValue的自动类型推断,改用Add方法显式指定SqlDbType.Date:
cmd.Connection = conn; conn.Open(); cmd.Parameters.AddWithValue("@userID", user); // 显式绑定参数类型 cmd.Parameters.Add("@datefrom", SqlDbType.Date).Value = startDate; cmd.Parameters.Add("@dateto", SqlDbType.Date).Value = endDate;
方案2:将DateOnly转换为DateTime
通过DateOnly.ToDateTime()方法转换为SQL兼容的DateTime类型:
cmd.Connection = conn; conn.Open(); cmd.Parameters.AddWithValue("@userID", user); // 转换为DateTime(TimeOnly.MinValue不影响date类型存储) cmd.Parameters.AddWithValue("@datefrom", startDate.ToDateTime(TimeOnly.MinValue)); cmd.Parameters.AddWithValue("@dateto", endDate.ToDateTime(TimeOnly.MinValue));
方案3:升级SqlClient版本
确保项目引用的Microsoft.Data.SqlClient NuGet包版本为5.0.0及以上,该版本已原生支持DateOnly与SQL date类型的映射,升级后可直接使用AddWithValue无需额外处理。
内容的提问来源于stack exchange,提问作者HPD71
相关产品推荐
相关产品推荐

