2

UWP アプリで拡張機能を使用して SQLite.NET を使用して、DateTime フィールドを含むオブジェクトを格納していますが、奇妙な結果が得られます。日付は本来あるべき状態から数時間ずれた状態で保存されているようで、DateTime の Day が翌日にずれることがあります。

このような Situation オブジェクトを含む Record という POCO クラスを保存しています。

public class Situation
{
    [PrimaryKey, AutoIncrement]
    public int SituationId { get; set; }

    public DateTime DateTime { get; set; }

    public string Description { get; set; }
}

状況を含む Record クラスは、次のようなリポジトリ パターンを介して SQLite を使用して保存されます (関連するメソッドのみを含めました)。

 internal class Repository<T> : IRepository<T> where T : class
{
    private SQLiteAsyncConnection asyncConn;

    public Repository(SQLiteAsyncConnection conn)
    {
        asyncConn = conn;
    }

    public async Task<T> GetByIdAsync(int id)
    {
        var entity = await asyncConn.GetWithChildrenAsync<T>(id);
        return entity;
    }

    public async Task InsertOrUpdateAsync(T entity)
    {
        await asyncConn.InsertOrReplaceWithChildrenAsync(entity);
    }
}

最後に、ConnectionManager クラスを使用してリポジトリの AsyncConnection を取得します。

public class ConnectionManager
{
    public static readonly string FileName = "db.sqlite";

    private static string path = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite");

    public static SQLiteAsyncConnection GetAsyncConnection()
    {
        var connString = new SQLiteConnectionString(path, storeDateTimeAsTicks: true);
        var connWithLock = new SQLiteConnectionWithLock(new SQLitePlatformWinRT(), connString);
        return new SQLiteAsyncConnection(() => connWithLock);
    }
}

この AsyncConnection は DateTimes を目盛りとして保存しますが、これが問題の原因である可能性があります。

あるケースでは、Repository.InsertOrUpdateAsync を使用して Record オブジェクトが格納される直前に、Situation.DateTime に次の値が設定されています。

DateTime = {2016-07-01 12:59:59 PM}

ティック = 636029747990010000

ただし、Repository.GetByIdAsync を使用してレコードをプルすると、DateTime の値は次のようになります。

DateTime = {2016-07-01 4:59:59 PM}

ティック = 636029891990010000

ご覧のとおり、SQLite が DateTime を格納する方法に問題があります。[Ticks] フィールドが変更され、新しい日付になりました。これがなぜなのかは100%わかりません。DateTime の精度に問題があることはわかっていますが、DateTime が Ticks として保存されている場合、Ticks フィールドは一致しないのでしょうか? なぜ彼らは変わるのですか?

DateTimes をティックとして格納する必要があると仮定すると、この問題を解決するにはどうすればよいですか? DateTime 時間を 12 に設定して、日を変更せずに数時間増減できるようにすることを考えていますが、これは明らかに理想的ではありません。

どんな助けでも大歓迎です。:)

4

1 に答える 1

1

デモを作成し、Ticks を使用してDateTime. 同じ問題が発生します。受信したオブジェクトのDateTimeプロパティをデバッグしました。SituationであることがわかりDateTime.KindますUtc。これはタイムゾーンの問題です。SQLite はDateTimeデフォルトで を UTC 時間に変換します。この問題を解決するには、DateTime.ToLocalTimeを使用して正しい現地時間を取得します。

コードは次のとおりです。

if (situation.DateTime.Kind == DateTimeKind.Utc)
{
     situation.DateTime = situation.DateTime.ToLocalTime();
}
于 2016-07-18T10:50:40.257 に答える