【问题标题】:Storing dynamic JSON data in db and search by key-value [closed]在数据库中存储动态 JSON 数据并按键值搜索 [关闭]
【发布时间】:2019-02-20 19:19:16
【问题描述】:

我需要在数据库中存储动态 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 由 admin-site 生成。管理员有一个面板,他可以在其中添加列、fieldType 和默认值(如果此下拉列表,则为值数组)

这个json转换成表格,用户在现场填写并存储到数据库中

要保存的数据如下所示:

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

任务:

  1. 在 DB 中存储用户的答案
  2. 按 DB 中的答案搜索(现场过滤器,一个或多个匹配项,例如问题 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;}

我不确定这是完成这项任务的最佳方式,如果有人分享他们的案例,我将不胜感激。

【问题讨论】:

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


    【解决方案1】:

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

    存储是一回事,查询是另一回事:为此,您必须直接对 DB 运行查询,或运行存储过程(查看 this SO answer

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

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

    SELECT
        tj.Id, QuestionData.questionId, QuestionData.questionValue
    FROM
        MyTableWithJson tj
        CROSS APPLY OPENJSON(tj.JsonContent)
        WITH ([questionId] INT '$.QuestionId', [questionValue] NVARCHAR(300) '$.Value') AS QuestionData
    WHERE
        QuestionData.type = 'multichoice' // supposing you have a type on this entity
    

    更多关于如何在Sql Server中查询JSON的例子here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-05
      • 1970-01-01
      • 2017-02-12
      • 1970-01-01
      • 2020-12-11
      • 2010-10-13
      • 1970-01-01
      • 2012-11-29
      相关资源
      最近更新 更多