我正在创建一个从数据库返回Key和Value的API。我想通过RowId返回一个数据。我在c#中使用存储过程和lambda表达式。我只是在获取存储过程的返回值后使用.ToList()。
这是我的示例代码:
SELECT
Id
,RowId
,Key
,Value
FROM
TableOne
WHERE
UserId = @userId AND RankType = @rankType
这是示例数据:
Id RowId Key Value
1 2 Name John Doe
2 2 Age 30
3 2 Position Developer
截至目前这是我得到的API响应:
{
"Key": Name,
"Value": John Doe
},
{
"Key": Age,
"Value": 30
},
{
"Key": Position,
"Value": Developer
}
这是我想要的API响应。如何将API响应格式化为此格式?
{
"Key": Name, "Value": John Doe,
"Key": Age, "Value": 30,
"Key": Position, "Value": Developer
},
方法1:
您可以编写如下查询。
select [Name], Age, Position
FROM
(
select [Value], [Key]
from TableOne
) d
pivot
(
max([Value])
for [Key] in ([Name], Age, Position)
) piv
您将获得如下输出。
+----------+-----+-----------+
| Name | Age | Position |
+----------+-----+-----------+
| John Doe | 30 | Developer |
+----------+-----+-----------+
现在在前端框架中使用等效模型映射此输出,您将获得所需的JSON,如下所示。
{"Name":"John Doe","Age":"30","Position":"Developer"}
方法2(直接从DB返回JSON作为字符串)
为此,您可以编写如下查询。
select [Name], Age, Position
FROM
(
select [Value], [Key]
from TableOne
) d
pivot
(
max([Value])
for [Key] in ([Name], Age, Position)
) piv
for json auto
方法3:
通常从DB
读取数据并使用LINQ
或simple if语句将其转换为具有3个属性的适当模型。