简体   繁体   English

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

[英]Serializable data types in SQLite.net

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. 简介:在SQLite.net驱动的SQLite数据库中(在WP8.1 SL上,但这不应该在这里)我正在添加基于给定对象的数据。 This object contains a custom type called Date . 此对象包含名为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. 实际问题:我该如何改进。 Ie How can I store a serialized version of Date directly. 即如何直接存储序列化版本的Date It should be in a way so that Date can be used as primary key. 它应该以某种方式使Date可以用作主键。 It is not important to me to have all the properties in Date available in single columns in a table. 在表中的单个列中将Date所有属性都可用对我来说并不重要。 I want to store Date itself in just one column. 我想将Date本身存储在一列中。

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. 目前的研究:为了尝试Google的答案,我偶然发现了SQLite.net的ISerializable接口,但我不确定如何使用它,因为它只有serialize方法但没有deserialize方法。

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

Known Issue(s): there should at least be a comment in the ISerializable class stating any usage requirement(s). 已知问题:在ISerializable类中至少应该有一条注释,说明任何使用要求。

Solution: your serializable class needs ctor that takes in the serializable type as a parameter . 解决方案:您的可序列化类需要ctor ,它将可序列化类型作为参数

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: 在SQLite持久化类中使用:

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

    public MySerializable MySerValues { get; private set; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM