将C#datetime转换为sql server datetime会引发错误

在C#中,值为{27-01-2017 12.00.00 AM}的DateTime属性在数据表中传递给具有UTT参数的过程。 UTT也具有相同的数据类型datetime。 我使用下面提供的通用方法。 我无法显式转换数据类型。

错误:将nvarchar数据类型转换为日期时间数据类型会导致超出范围的值。 表值参数@UttParameter的数据不符合参数的表类型。
SQL Server错误是:242,状态:3
该语句已终止。

 public static DataTable ToDataTable(IList items, bool usePropertyMappingName = false) { DataTable dataTable = null; if (items != null) { using (dataTable = new DataTable(typeof(T).Name)) { dataTable.Locale = System.Globalization.CultureInfo.InvariantCulture; // Get all the properties. PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo prop in props) { string columnName = prop.Name; if (usePropertyMappingName) { var mappingAttribute = prop.GetCustomAttributes(typeof(PropertyMappingAttribute), true).FirstOrDefault() as PropertyMappingAttribute; if (mappingAttribute != null && !string.IsNullOrEmpty(mappingAttribute.Name)) { columnName = mappingAttribute.Name; } } // Setting column names as Property names. dataTable.Columns.Add(columnName, prop.PropertyType); } foreach (T item in items) { var values = new object[props.Length]; for (int i = 0; i < props.Length; i++) { // Inserting property values to data table rows. values[i] = props[i].GetValue(item, null); } dataTable.Rows.Add(values); } } } return dataTable; } 

您的代码 – 就像现在一样 – 将在字符串级别上传输任何值 。 这是一个非常糟糕的方法 。 发生的隐式转换在很大程度上取决于系统的设置(语言和文化)。 最糟糕的是:在您测试它时,这可能对您的计算机有用,但在客户的系统上,它会打破奇怪的消息。 快乐调试:-(

像这样更改你的代码

 foreach (PropertyInfo prop in props) { // Setting column names as Property names. if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) dataTable.Columns.Add(prop.Name, prop.PropertyType.GetGenericArguments()[0]); else dataTable.Columns.Add(prop.Name, prop.PropertyType); } 

这将添加列 – 即使这是一个可空类型 – 具有正确的数据类型。

学分: 这个答案对我有帮助

更新更简单

(请在链接答案下方的评论中向Yves M.致谢)

 foreach (PropertyInfo prop in props) { // Setting column names as Property names. dataTable.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType); } 

删除引号

“@UttParameter”

 @UttParameter 

您正在使用InvariantCulture作为DataTable区域设置。 不变文化期望Date采用yyyy-MM-dd格式。