SQLite.net 中的可序列化数据类型

Serializable data types in SQLite.net

简介: 在 SQLite.net 驱动的 SQLite 数据库中(在 WP8.1 SL 上,但这在这里无关紧要)我添加的数据基于给定的对象。该对象包含一个名为 Date 的自定义类型。直到现在,我还没有将 属性 存储在数据库中,而是使用另一个 属性 作为解决方法。

[Ignore]
public Date Date { get; set; }

[PrimaryKey]
public DateTime DateInternal
{
    get { return Date.ToDateTime(); }
    set { Date = new Date(value); }
}

虽然这很好用,但我觉得这不是最好的方法。

实际问题:我该如何改进。 IE。如何直接存储 Date 的序列化版本。它应该是 Date 可以用作主键的方式。在 table 的单列中提供 Date 中的所有属性对我来说并不重要。我想将 Date 本身存储在一列中。

当前研究: 在尝试 Google 寻找答案时,我偶然发现了 SQLite.net 的 ISerializable 界面,但我不确定如何使用它,因为它只有 serialize 方法但没有 deserialize 方法。

namespace SQLite.Net
{
    public interface ISerializable<T>
    {
        [PublicAPI]
        T Serialize();
    }
}

已知问题:至少应该在ISerializable class 说明任何使用要求。

  • 因为没有,所以提交了this SQLite.Net-PCL Issue。它还提到了修复(例如满足接口的构造函数假设)

解决方案: 你的序列化 class 需要 ctor 作为参数的可序列化类型.

一个例子:

Class w/two 整数:

public struct MySerializable : ISerializable<string>
{
    public int Value1 { get; set; }
    public int Value2 { get; set; }

    // ****See Here: Ctor taking serialized type to restore field vals
    public MySerializable(string serializedData) : this()
    {
        var stringVals = serializedData.Split(',');
        Value1 = Convert.ToInt32(stringVals[0]);
        Value2 = Convert.ToInt32(stringVals[1]);
    }

    public override string ToString()
    {
        return string.Format("{0},{1}", Value1, Value2);
    }

    // ****See  Here: serializing field vals to string
    public string Serialize()
    {
        return ToString();
    }
}

正在 SQLite 中使用 class:

public class MyTable
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; private set; }

    public MySerializable MySerValues { get; private set; }
}