C# 在数据库中存储动态JSON数据并按键值搜索
我需要在数据库中存储动态json并按键值搜索 我有jsonC# 在数据库中存储动态JSON数据并按键值搜索,c#,asp.net,sql-server,entity-framework,entity-framework-core,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, "Ty
[{
"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由管理员站点生成。管理员有一个面板,可以在其中添加列、字段类型和默认值(或值数组,如果是此下拉列表)
此json转换为表单,用户在站点上填写表单并存储到DB
要保存的数据如下所示:
[{
"QuestionId": 1,
"Value": "Test",
},
{
"QuestionId": 2,
"Value": true,
},
{
"QuestionId": 4,
"Value": "true",
"Value": "2018-09-16T20:03:57.551Z"
}
]
任务:
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;}
public ICollection答案{get;set;}
我不确定这是执行此任务的最佳方式,如果有人能与您分享他们的案例,我将不胜感激。使用最新的SQL Server功能(因为),您可以将JSON存储为文本并对其进行查询 存储是一回事,查询是另一回事:要做到这一点,您必须直接对数据库运行查询,或者运行存储过程(请参阅) 最后,您必须编写特定的SQL语句,以便能够查询JSON中的项(如果您有很多行,这也是一个好主意) 至于查询本身,它看起来是这样的:
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的更多示例