Npgsql DataReader将DateTime类型用于没有时区的时间而不是TimeSpan

时间:2015-09-14 18:32:04

标签: c# postgresql npgsql

我正在使用Npgsql在Postgres中选择一个表。此表格中包含auction_time类型的列time without time zone。读者返回的数据表会将此列auction_time转换为DateTime而不是TimeSpan,如我所料。将数据批量复制到类型为time(7)的MS SQLServer中的另一个表时,这会导致问题。

这是我选择的地方:

using (NpgsqlConnection connection = new NpgsqlConnection(String.Format(PropertyDataDB.ConnectionStringWithSearchPath, schemaName)))
{
    connection.Open();
    NpgsqlCommand command = new NpgsqlCommand
    {
        CommandText = commandText,
        Connection = connection
    };

    using (NpgsqlDataReader dataReader = command.ExecuteReader())
    {
        DataTable dt = new DataTable();
        //dt = dataReader.GetSchemaTable();
        dt.Load(dataReader);

        BulkCopy(destinationTable, dt);
    }
}

因此,dt中的auction_type将为DateTime类型,并且所有时间都会在其前面附加日期1/1/0001。我该如何防止这种情况?

感谢。

3 个答案:

答案 0 :(得分:2)

另一个修复是将Npgsql升级到版本3.x,此问题已修复。 http://www.npgsql.org/doc/release-notes/3.0.html

答案 1 :(得分:1)

这就是我最终要做的事情,如果你需要留在verison 2.x上,只做这样的事情。它有效,但我根本不喜欢它。我只是克隆数据表,更改数据类型,然后执行" cast"需要的时候。

using (NpgsqlConnection connection = new NpgsqlConnection(String.Format(PropertyDataDB.ConnectionStringWithSearchPath, schemaName)))
{
    connection.Open();
    NpgsqlCommand command = new NpgsqlCommand
    {
        CommandText = commandText,
        Connection = connection
    };

    using (NpgsqlDataReader dataReader = command.ExecuteReader())
    {
        DataTable dt = new DataTable();
        dt.Load(dataReader);

        if (dt.Columns.Contains("auction_time"))
        {
            DataTable clone = dt.Clone();
            clone.Columns["auction_time"].DataType = typeof(TimeSpan);
            foreach (DataRow row in dt.Rows)
            {
                DataRow newRow = clone.NewRow();
                foreach (DataColumn column in dt.Columns)
                {
                    if (column.ColumnName == "auction_time" && !row.IsNull(column.Ordinal))
                    {
                        newRow[column.Ordinal] = ((DateTime)row[column.Ordinal]).TimeOfDay;
                    }
                    else
                    {
                        newRow[column.Ordinal] = row[column.Ordinal];
                    }
                }
            }
            dt = clone;
        }

        BulkCopy(destinationTable, dt);
    }
}

答案 2 :(得分:0)

我的解决方案:

class Model
{
    public readonly static string tableName = "tb_name";
    public Int32 id {get; private set;}
    public string auth_token {get; private set;}
    public TimeSpan column_time {get; set;} // this is the target !!

    /* more columns for model object   here.. */

    public static NpgsqlCommand Query(string sql = null )
    {
        // treturn new NpgsqlCommand from my global NpgsqlConnection  definition
        return Connection.CreateObject().Query(sql); 
    }

    public static Model FindByPk(int id)
    {
        NpgsqlCommand query = Query(string.Format("select  * from {0} where id = @id order by id asc limit 1" , tableName ));
        query.Parameters.AddWithValue("@id", id);

        NpgsqlDataReader reader = query.ExecuteReader();
        if(reader.HasRows == false)
            return null;

        Model obj = new Model();
        return (obj.SetDbProperties(reader)) ? obj : null;
    }

    protected bool SetDbProperties(NpgsqlDataReader reader)
    {
        if(reader.IsClosed)
            return false;
        try{
            reader.Read();

            for (int i = 0; i < reader.FieldCount; i++)
            {
                string key = reader.GetName(i);

                if(reader.GetValue(i) == DBNull.Value )
                    continue;

                //@todo add dinamic setter by key value
                // https://titiandragomir.wordpress.com/2009/12/22/getting-and-setting-property-values-dynamically/
                switch(key)
                {
                    case "id":
                        this.id =  reader.GetInt32(i);
                        break;
                    case "auth_token":
                        this.auth_token = reader.GetString(i);
                        break;

                    case "column_time":
                            // solution!!!!
                            var colValue = reader.GetTime(i);
                            this.horario_dia1_init = new TimeSpan(0, colValue.Hours , colValue.Minutes, colValue.Seconds, colValue.Microseconds ); 
                        break;
                }
            }
            reader.Close();
            return true;
        }
        catch(Exception e){
            Console.WriteLine(e.Message);
            return false;
        }
    }
}

示例用法:

    public static void Main(string[] args)
    {

        Model model = Model.FindByPk(1);
        if(model == null)
            Console.WriteLine("record not found");

        else {
            Console.WriteLine("model.id               {0}", model.id);
            Console.WriteLine("model.auth_token       {0}", model.auth_token);
            Console.WriteLine("model.column_time      {0}", model.column_time); 
        }

        Console.Read();
    }