简体   繁体   English

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

[英]Conversion of C# datetime to sql server datetime is throwing an error

In C# a DateTime property with value {27-01-2017 12.00.00 AM} is being passed in a data table to a procedure with an UTT parameter. 在C#中,值为{27-01-2017 12.00.00 AM}的DateTime属性在数据表中传递给具有UTT参数的过程。 UTT also has the same datatype datetime. UTT也具有相同的数据类型datetime。 I am using the generic method provided below. 我正在使用下面提供的通用方法。 I cannot explicitly convert data type. 我无法显式转换数据类型。

Error : The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value. 错误:将nvarchar数据类型转换为日期时间数据类型会导致超出范围的值。 The data for table-valued parameter @UttParameter doesn't conform to the table type of the parameter. 表值参数@UttParameter的数据不符合参数的表类型。
SQL Server error is: 242, state: 3 SQL Server错误是:242,状态:3
The statement has been terminated. 该语句已终止。

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;
    }

Remove the quotation marks 删除引号

"@UttParameter" “@UttParameter”

@UttParameter

You are using InvariantCulture as DataTable locale. 您正在使用InvariantCulture作为DataTable语言环境。 Invariant culture expects Date to be in yyyy-MM-dd format. 不变文化期望Date采用yyyy-MM-dd格式。

Your code - as it is now - will transfer any value on string level . 您的代码 - 就像现在一样 - 将在字符串级别传输任何值 This is a really bad approach . 这是一个非常糟糕的方法 The implicit conversions taking place are highly depending on your system's settings (language and culture). 发生的隐式转换在很大程度上取决于系统的设置(语言和文化)。 The worst part is: This might work all great on your machine while you are testing it, but on a customer's system it breaks with strange messages. 最糟糕的部分是:在您测试它时,这可能在您的计算机上运行良好,但在客户的系统上,它会打破奇怪的消息。 Happy Debugging :-( 快乐调试:-(

Change your code like this 像这样更改你的代码

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);
}

This will add the column - even if this is a nullable type - with the correct data type. 这将添加列 - 即使这是一个可空类型 - 具有正确的数据类型。

credits: This answer helped me 学分: 这个答案对我有帮助

UPDATE Even simpler 更新更简单

(thx to Yves M. in a comment below the linked answer) (请在链接答案下方的评论中向Yves M.发送)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM