无法将 DateTime 隐式转换为 Timespan

Cannot implicitly convert DateTime to Timespan

Sql 服务器的变量 TEST_TIME 数据类型为 Time(7)
我在 C# 中创建了表,它自动分配了 Timespan 数据类型。
现在,我正在尝试将 csv 文件数据上传到 SQL 数据库,它给我一个错误“无法将 DateTime 隐式转换为 Timespan”。解决此问题的最佳方法是什么? 用户首先选择 CSV 文件:

    private void button8_Click(object sender, EventArgs e)  
        {  
               try  
                    {  
                        using (OpenFileDialog openfiledialog1 = new OpenFileDialog()   
                        {Filter = "Excel Workbook 97-2003|*.xls|Excel Workbook|*.xlsx|Excel Workbook|*.xlsm|Excel Workbook|*.csv|Excel Workbook|*.txt", ValidateNames = true })                      
                        {   
--After some IFs--  

    else if (openfiledialog1.FilterIndex == 4)
                                {

                                    DataTable oDataTable = null;
                                    int RowCount = 0;
                                    string[] ColumnNames = null;
                                    string[] oStreamDataValues = null;
                                    //using while loop read the stream data till end
                                    while (!oStreamReader.EndOfStream)
                                    {
                                        String oStreamRowData = oStreamReader.ReadLine().Trim();
                                        if (oStreamRowData.Length > 0)
                                        {
                                            oStreamDataValues = oStreamRowData.Split(',');
                                            //Bcoz the first row contains column names, we will populate 
                                            //the column name by
                                            //reading the first row and RowCount-0 will be true only once
                                            if (RowCount == 0)
                                            {
                                                RowCount = 1;
                                                ColumnNames = oStreamRowData.Split(',');
                                                oDataTable = new DataTable();

                                                //using foreach looping through all the column names
                                                foreach (string csvcolumn in ColumnNames)
                                                {
                                                    DataColumn oDataColumn = new DataColumn(csvcolumn.ToUpper(), typeof(string));

                                                    //setting the default value of empty.string to newly created column
                                                    oDataColumn.DefaultValue = string.Empty;

                                                    //adding the newly created column to the table
                                                    oDataTable.Columns.Add(oDataColumn);
                                                }
                                            }
                                            else
                                            {
                                                //creates a new DataRow with the same schema as of the oDataTable            
                                                DataRow oDataRow = oDataTable.NewRow();

                                                //using foreach looping through all the column names
                                                for (int i = 0; i < ColumnNames.Length; i++)
                                                {
                                                    oDataRow[ColumnNames[i]] = oStreamDataValues[i] == null ? string.Empty : oStreamDataValues[i].ToString();
                                                }

                                                //adding the newly created row with data to the oDataTable       
                                                oDataTable.Rows.Add(oDataRow);
                                            }
                                        }
                                    }
                                    result.Tables.Add(oDataTable);
                                    //close the oStreamReader object
                                    oStreamReader.Close();
                                    //release all the resources used by the oStreamReader object
                                    oStreamReader.Dispose();
                                    dataGridView5.DataSource = result.Tables[oDataTable.TableName];
                                } 

这是代码:

    private void button9_Click(object sender, EventArgs e)
            {

                try
                {               


                    DataClasses1DataContext conn = new DataClasses1DataContext();
        else if (textBox3.Text.Contains("GEN_EX"))
            {
                foreach (DataTable dt in result.Tables)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        GEN_EX addtable = new GEN_EX()
                        {

                            EX_ID = Convert.ToByte(dr[0]),
                            DOC_ID = Convert.ToByte(dr[1]),
                            PATIENT_NO = Convert.ToByte(dr[2]),
                            TEST_DATE = Convert.ToDateTime(dr[3]),                    
                            **TEST_TIME = Convert.ToDateTime((dr[4])),**

                        };
                        conn.GEN_EXs.InsertOnSubmit(addtable);
                    }
                }
                conn.SubmitChanges();
                MessageBox.Show("File uploaded successfully");
            }  
     else
        {
            MessageBox.Show("I guess table is not coded yet");
        }
}

编辑

TEST_TIME表示HH:MM:SS
类型化数据集定义为:

public virtual int Update(
                    byte EX_ID, 
                    byte DOC_ID, 
                    byte PATIENT_NO, 
                    System.DateTime TEST_DATE, 
                    System.TimeSpan TEST_TIME) 

根据您的输入,dr[4] 表示 hours:minutes:seconds 格式的时间值,我建议采用以下解决方案。

private TimeSpan GetTimeSpan(string timeString)
{
    var timeValues = timeString.Split(new char[] { ':' });
    //Assuming that timeValues array will have 3 elements.
    var timeSpan = new TimeSpan(Convert.ToInt32(timeValues[0]), Convert.ToInt32(timeValues[1]), Convert.ToInt32(timeValues[2]));
    return timeSpan;
}

使用上面的方法如下。

else if (textBox3.Text.Contains("GEN_EX"))
{
    foreach (DataTable dt in result.Tables)
    {
        foreach (DataRow dr in dt.Rows)
        {
            GEN_EX addtable = new GEN_EX()
            {

                EX_ID = Convert.ToByte(dr[0]),
                DOC_ID = Convert.ToByte(dr[1]),
                PATIENT_NO = Convert.ToByte(dr[2]),
                TEST_DATE = Convert.ToDateTime(dr[3]),                    
                **TEST_TIME = GetTimeSpan(dr[4].ToString()),**

            };
            conn.GEN_EXs.InsertOnSubmit(addtable);
        }
    }
    conn.SubmitChanges();
    MessageBox.Show("File uploaded successfully");
}

这应该会给你想要的价值。如果 dr[4] 的值不是 hours:minutes:seconds 格式,您将面临运行时问题。那我就交给你了。

首先,Timespan 和 DateTime 是两种不同的类型,没有可用的隐式转换。由于 Timespan 是两个 DateTime 之间的时间值,您需要知道用于开始测量 Timespan 的参考时间 (DateTime)。

例如,它可能来自 DateTime dtReferential = new DateTime(1900, 01, 01);

为了提供 SQL Timespan 值,您需要为其提供 C# Timespan!将 TEST_TIME 值更改为时间跨度。最后,给它减去你的参考时间的值。

使用前面的例子:

else if (textBox3.Text.Contains("GEN_EX"))
{
    foreach (DataTable dt in result.Tables)
    {
        foreach (DataRow dr in dt.Rows)
        {
            GEN_EX addtable = new GEN_EX()
            {

                EX_ID = Convert.ToByte(dr[0]),
                DOC_ID = Convert.ToByte(dr[1]),
                PATIENT_NO = Convert.ToByte(dr[2]),
                TEST_DATE = Convert.ToTimespan(dr[3]),                    
                TEST_TIME = dtReferential.Subtract(Convert.ToDateTime(dr[4]))

            };
            conn.GEN_EXs.InsertOnSubmit(addtable);
        }
    }
    conn.SubmitChanges();
    MessageBox.Show("File uploaded successfully");
}