首页 > 解决方案 > 从 SQL 服务器获取 DateTime 并将其分配给属性

问题描述

我有以下课程:

public class Invoice
{
     public int ID {get; set;}
     public DateTime creationDate {get; set;}
}

我在我的 SQL-Server 数据库中保存了具有以下属性的发票:

invoice
 - invoiceID [int, null] 
 - creationDate [datetime, null]

我的日期包含以下格式:2018-07-31 00:00:00.000

但是,当我收到带有以下内容的发票时

SqlCommand command = new SqlCommand(@"SELECT id, creationDate FROM invoice WHERE invoiceID = @invoiceID", conn);
        command.Parameters.Add("@InvoiceID", SqlDbType.Int).Value = InvoiceID;
        {
            conn.Open();
            SqlDataReader reader = command.ExecuteReader();
            if (reader.Read())
            {
                temp.ID = int.Parse(reader["id"].ToString());
                temp.InvoiceDate = Convert.ToDateTime(reader["creationDate"]).ToString("yyyy/MM/dd");
            }
            conn.Close();
        }

但是,当我运行我的代码时,我得到了错误:

SqlDateTime 溢出。必须在 1753 年 1 月 1 日上午 12:00:00 到 9999 年 12 月 31 日晚上 11:59:59 之间

我究竟做错了什么?

标签: c#sqlsql-serverdatetime

解决方案


如果您有一个健全的数据库架构,则该createDate已经是一个 DateTime 值。转换字符串只会让你自己受伤。id和相同int

using (var conn = new SqlConnection("connection string here"))
using (var command = new new SqlCommand(@"SELECT id, creationDate FROM invoice WHERE invoiceID = @invoiceID", conn))
{
    command.Parameters.Add("@InvoiceID", SqlDbType.Int).Value = InvoiceID;
    conn.Open();
    SqlDataReader reader = command.ExecuteReader();
    if (reader.Read())
    {
        temp.ID = (int)reader["id"];
        temp.InvoiceDate = (DateTime)reader["creationDate"];
    }
}

creationDate如果can be ,您确实需要更加小心NULL,但否则,简单的演员阵容就足够了。


推荐阅读