在数据库中存储动态JSON数据并按键值搜索

时间:2018-09-16 20:14:23

标签: c# asp.net sql-server entity-framework entity-framework-core

我需要在数据库中存储动态json并按键值进行搜索

我有json

    [{
      "id": 1,
      "Type": "string",
      "FieldName" : "Test",
      "Value": "Test", 
    }, {
      "id": 2,
      "Type": "bool",
      "FieldName" : "Test2",
      "Value": "true", 
     "id": 2,
      "Type": "dropdown",
      "FieldName" : "dropDownTest",
      "Value": [{"text":"my placeholder", "Value": "myTestValue"}, {"text":"my placeholder2", "Value": "myTestValue2"}]
    }, 
    {
      "id": 3,
      "Type": "int",
      "Value": 133
},
{
      "id": 4,
      "Type": "DateTime",
      "Value": ""
}]

此json由管理站点生成。管理员有一个面板,他可以在其中添加列,fieldType和默认值(或此下拉列表中的值数组)

此json转换为表单,用户可以在网站上填写并将其存储到数据库

用于保存的数据如下:

   [{
      "QuestionId": 1,
      "Value": "Test", 
      }, 
    {
      "QuestionId": 2,
      "Value": true, 
    },
    {
      "QuestionId": 4,
      "Value": "true", 
      "Value": "2018-09-16T20:03:57.551Z"
    }
    ]

任务:

  1. 在数据库中为用户存储答案
  2. 按答案在数据库中搜索(网站上的过滤器,一个或多个匹配项,例如问题1和4个匹配项(值是“测试”,日期大于昨天...))
  3. 快速搜索的最佳结构

我的愿景: 创建一个实体

public class QuestionEntity
{
    public int id { get; set; }
    public string Type { get; set; }
    public string FieldName { get; set; }
    public string Value { get; set; }
}

并创建一个答案实体

public class Answer
{
    public int QuestionId { get; set; }
    public string Value { get; set; }
}

并将此答案添加为用户集合

public ICollection<Answer> Answers{get; set;}

我不确定这是什么最佳方法,如果有人可以分享他们的案例,我将不胜感激。

1 个答案:

答案 0 :(得分:0)

使用最新的SQL Server功能(自2016起),您可以将JSON存储为文本并对其进行查询。

存储是一回事,查询是另一回事:要这样做,您将不得不直接对数据库运行查询,或者运行存储过程(请查看this SO answer

然后,最后,您将必须编写特定的SQL语句以能够查询JSON中的项目(如果行很多,having indexes on JSON properties也可能是个好主意)。

对于查询本身,它看起来像这样:

{{1}}

有关如何在Sql Server here中查询JSON的更多示例