Serializable data types in SQLite.net

3.3k views Asked by At

Introduction: In a SQLite.net powered SQLite database (on WP8.1 SL, but this shouldn't matter here) I'm adding data based on a given object. This object contains a custom type called Date. Until now I don't store that property in the DB but use another property as workaround.

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

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

While this works fine I feel this is not the best way to do that.

Actual Question: How can I improve that. I.e. How can I store a serialized version of Date directly. It should be in a way so that Date can be used as primary key. It is not important to me to have all the properties in Date available in single columns in a table. I want to store Date itself in just one column.

Current Research: In an attempt to Google for an answer I stumbled upon SQLite.net's ISerializable interface but I'm unsure how to use it as it only has a serialize method but no deserialize method.

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

There are 1 answers

0
bunkerdive On BEST ANSWER

Known Issue(s): there should at least be a comment in the ISerializable class stating any usage requirement(s).

  • Because there isn't, this SQLite.Net-PCL Issue was submitted. It also mentions the fix (e.g. satisfying the interface's constructor assumption)

Solution: your serializable class needs ctor that takes in the serializable type as a parameter.

An Example:

Class w/two ints:

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();
    }
}

Being used in an SQLite-persisted class:

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

    public MySerializable MySerValues { get; private set; }
}