C#反序列化,然后插入SQLite数据库

时间:2017-07-18 22:08:05

标签: c# json sqlite

我有模型项目的以下JSON,我无法更改:

[
    {
        "id": 3,
        "description": "Project A"
    },
    {
        "id": 6,
        "description": "Project B",
        "updated_at": "2017-07-13T09:30:51+02:00",
        "created_at": "2017-07-13T09:30:51+02:00"
    }
]

我有以下用于模型任务的JSON,我无法更改:

[
    {
        "id": 3,
        "project": {
            "id": 3,
            "description": "Project A"
        },
        "description": "Task 1"
    },
    {
        "id": 6,
        "project": {
            "id": 3,
            "description": "Project A"
        },
        "description": "Task 2"
    },
    {
        "id": 9,
        "project": {
            "id": 3,
            "description": "Project A"
        },
        "description": "Task 3"
    },
    {
        "id": 12,
        "project": {
            "id": 6,
            "description": "Project B"
        },
        "description": "Task 4"
    }
]

我有以下两种型号:

using SQLite.Net.Attributes;
using SQLiteNetExtensions.Attributes;

namespace BettyMultiModel.Resources.Model
{
    public class Models
    {

    }

    class Project : Models
    {

        public int Id { get; set; }
        public string Description { get; set; }

    }

    class Task : Models
    {

        public int Id { get; set; }
        public string Description { get; set; }   

    }
}

我使用此方法将JSON引入SQLite数据库:

// Insert Records of type TType into database.
private async Task<string> InsertRecords<TType>(HttpResponseMessage response)
        where TType : Models
{
    try
    {
        DataBase db = new DataBase();

        string responseString = await response.Content.ReadAsStringAsync();
        var responseBody = JsonConvert.DeserializeObject<List<TType>>(responseString);


        foreach (TType item in responseBody)
        {
            bool resultInsert = db.Insert(item);
        }

        return ResponseToMessage(response, "Insert Records");
    }
    catch (Exception ex)
    {
        Log.Info("DeserializeObject", ex.Message);
        throw;
    }            

}

当我只想拥有两个模型的Id和Description属性时,这很好用。但我还想在Task模型中存储Project模型和Task模型/项目id之间的关系。

当我使用http://json2csharp.com/处的任务解析JSON时,我得到以下有关模型的建议:

public class Project
{
    public int id { get; set; }
    public string description { get; set; }
}

public class RootObject // Which is Task
{
    public int id { get; set; }
    public Project project { get; set; }  // <-------- Extra property
    public string description { get; set; }
}

使用这样的模型 - 将RootObject重命名为Task - 会导致异常:NotSupportedException:不了解BettyMultiModel.Resources.Model.Project

所以我将课程改为:

using SQLite.Net.Attributes;
using SQLiteNetExtensions.Attributes;

namespace BettyMultiModel.Resources.Model
{
    public class Models
    {

    }

    class Project : Models
    {

        [PrimaryKey]
        public int Id { get; set; }
        public string Description { get; set; }

    }

    class Task : Models
    {

        [PrimaryKey]
        public int Id { get; set; }
        public string Description { get; set; }

        [OneToMany]
        public Project project { get; set; }

    }
}

不再抛出异常,但是当我查看db文件时,仍然只有Id和Description列,并且没有引用2个模型之间的关系。

我在这里缺少什么?

编辑:添加了创建表格的方法

public void ClearTable<TType>()
        where TType : Models
{
    try
    {
        Log.Info("Folder DB: ", dbPath);

        using (var connection = new SQLiteConnection(platform, dbPath))
        {
            connection.DropTable<TType>();
            connection.CreateTable<TType>();
        }
    }
    catch (SQLiteException ex)
    {
        Log.Info("SQLiteEx", ex.Message);
    }

}

编辑:差不多......

我也犯了一个小错误,一个项目有很多任务,所以属性应该是[ManyToOne]。 db中的表现在看起来不错。项目ID未插入Task模型中的ProjectId列中。每行都有值0.我想我需要弄清楚如何将嵌套项目对象的id映射到类Task的ProjectId属性。

我尝试过像这样使用Newtonsoft.Json命名空间,它在Task模型中插入1行,然后因为记录了id的唯一性而开始抛出错误。 JsonProperty(&#34; id&#34;)将其标识为任务的ID,而不是项目:

[JsonProperty("id"), ForeignKey(typeof(Project))]
public int ProjectId { get; set; }

现在是这些模型:

class Project : Models
{

    [PrimaryKey]
    public int Id { get; set; }

    public string Description { get; set; }

}

class Task : Models
{

    [PrimaryKey]
    public int Id { get; set; }

    public string Description { get; set; }

    [ForeignKey(typeof(Project))]
    public int ProjectId { get; set; }

    [ManyToOne]
    public Project Project { get; set; }

}

1 个答案:

答案 0 :(得分:1)

假设您在问题中使用的是Twin Coders SQLite-Net-Extensions软件包,我认为您的模型定义方式存在错误。

如果查看链接的Bitbucket页面中的多对一部分,除ForeignKey属性外,还需要定义ManyToOne属性。这是他们的示例(请注意Person类上的Bus和BusId属性):

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

    public string PlateNumber { get; set; }
}

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

    public string Name { get; set; }

    [ForeignKey(typeof(Bus))]
    public int BusId { get; set; }

    [ManyToOne]
    public Bus Bus { get; set; }
}

使用您的代码,我相信您所要做的就是使用以下模型:

class Project : Models
{
    [PrimaryKey]
    public int Id { get; set; }

    public string Description { get; set; }

    // The id of the task used in the relationship (this gets stored in the DB)
    [ForeignKey(typeof(Task))]
    public int TaskId { get; set; }

    // Meaning you have many projects to one task
    [ManyToOne]
    public Task Task { get; set; }
}

class Task : Models
{
    [PrimaryKey]
    public int Id { get; set; }

    public string Description { get; set; }
}