c# - 在 Dapper 中使用 Protocol Buffer 模型时如何将 C# ticks 映射到 PostgreSQL 时间戳?

标签 c# postgresql dapper protobuf-net npgsql

我在我的应用程序中使用 protobuf-net 将记录的数据从远程站点发送到服务器。有多种数据类型 - 其中一种的示例消息如下:

message Sample {
    required int64 recording_time = 1; // UTC Timestamp in Ticks
    required double x_position = 2;
    required double y_position = 3;
    required double x_velocity = 4;
    required double y_velocity = 5;
}

在服务器上,对象存储在 PostgreSQL 数据库中。 Protocol Buffer (proto2) 消息中的所有 double 字段都映射到 PostgreSQL 中的 double 字段。时间戳字段 uint64 recording_time 必须映射到数据库中的 timestamp with time zone 字段。

我想使用相同的 C# 类(具有 ProtoContract 属性)在客户端序列化 Sample,并使用 Dapper 进行数据库操作(可能带有扩展名,例如 FastCRUD)。

这需要在ticks(C# 类型:long)和timestamp with time zone(C# 类型:日期时间)。在不创建第二个类的情况下实现这一点的最佳方法是什么?

这就是我目前将对象写入数据库的方式:

string sql = "COPY samples (recording_time, x_position, y_position, x_velocity, y_velocity) FROM STDIN (FORMAT BINARY)";
using (var writer = conn.BeginBinaryImport(sql))
{
    foreach (Sample sample in sampleList)
    {
        writer.StartRow();

        writer.Write(new DateTime(sample.RecordingTime, DateTimeKind.UTC), NpgsqlTypes.NpgsqlDbType.TimestampTZ);

        writer.Write(sample.X_Position, NpgsqlTypes.NpgsqlDbType.Double);
        writer.Write(sample.Y_Position, NpgsqlTypes.NpgsqlDbType.Double);
        writer.Write(sample.X_Velocity, NpgsqlTypes.NpgsqlDbType.Double);
        writer.Write(sample.Y_Velocity, NpgsqlTypes.NpgsqlDbType.Double);

    }
}

这就是我想写入数据库的方式:

foreach (Sample sample in sampleList)
{
    conn.Insert<Sample>(sample);
}

并使用相应的Query方法进行检索。

最佳答案

I want to use the same C# class (with ProtoContract attribute) to serialize Sample on the client, and also with Dapper for database operations (perhaps with an extension, e.g. FastCRUD).

就我个人而言,我认为这就是问题所在 - 试图用同一个对象做两件截然不同的事情。然而!这不一定是不可能的。特别要注意的是,protobuf-net 很乐意与私有(private)成员一起工作。所以一个选择可能是:

public WhateverYouNeedForTheDatabase Foo { get; set; }

[ProtoMember(someNumber)]
private WhateverYouNeedForTheSerializer FooSerialized {
    get { return FromX(Foo); }
    set { Foo = ToX(value); }
}

可以用 dapper 做类似的事情,但不太方便。特别是,在您的情况下:

public DateTime RecordingTime { get; set; }

[ProtoMember(1)]
private long RecordingTimeSerialized {
    get { return DateTimeToUnixTime(RecordingTime); }
    set { RecordingTime = UnixTimeToDateTime(value); }
}

这没有额外的存储要求(没有额外的字段)。

关于c# - 在 Dapper 中使用 Protocol Buffer 模型时如何将 C# ticks 映射到 PostgreSQL 时间戳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39876167/

相关文章:

c# - 在控制台中显示 UTF-8 字符

sql - 如何从两个只有 ID 重叠的表中获取最大值?

sql - 如何获取PostgreSQL中每五分之一数据的行数

oracle - 在 Oracle 中使用 Dapper QueryMultiple

c# - 使用 dapper 为 MySql 附加参数

tsql - Dapper QueryMultiple 存储过程 w/o 映射到对象

c# - 需要正则表达式来替换仅由字母或数字包围的所有符号

c# - 从大型数据库中检索行时优化灵活的 Linq to Entity 标准的性能

c# - 我的应用域不会卸载

python - Postgres 中 'money' 和 'OID' 的 sqlalchemy 等效列类型是什么?