【发布时间】:2017-01-27 16:57:06
【问题描述】:
在 C# 中,值 {27-01-2017 12.00.00 AM} 的 DateTime 属性正在数据表中传递给具有 UTT 参数的过程。 UTT 也具有相同的数据类型 datetime。我正在使用下面提供的通用方法。我无法显式转换数据类型。
错误:将 nvarchar 数据类型转换为 datetime 数据类型 导致超出范围的值。表值参数的数据 @UttParameter 不符合参数的表类型。
SQL Server 错误为:242,状态:3
声明已终止。
public static DataTable ToDataTable<T>(IList<T> 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;
}
【问题讨论】:
-
您没有将其作为 datetime 传递,而是将其作为 string 传递。您需要发布在 C# 中配置参数值的代码,包括该参数及其类型。如果您将它作为 datetime 传递,则不会进行转换,因此您遇到转换错误这一事实意味着您并没有真正按照您的想法或所说的去做。跨度>
-
SQL server 和你的服务器/机器的区域设置是否相同?
-
@Lasse V. Karlsen,有一个 List
,Class1 有许多属性,其中 datetime 是属性之一。有一种通用方法可以将项目列表转换为数据表。没有发生显式的数据类型转换。 -
@Vijayakrishna,是一样的。
-
有一个通用方法可以将项目列表转换为数据表:显示代码,至少是处理日期时间值的部分...
标签: c# sql-server-2012