如何使用Dapper从列动态更改的表中提取数据

问题描述 投票:0回答:1

由于客户的新要求,我面临一个问题。我有一张名为

Tasks
的桌子和一张名为
Codes
的桌子。

Tasks
表:

身份证 任务名称
1 二维
2 3D

Codes
桌子

身份证 代号 对于二维 对于3D
1 二维 1 0
2 3D 0 1

现在用户可以单击前端的按钮在任务表中添加新条目。相应地,

Codes
表中也应添加一个新列。例如: 新
Tasks
表:

身份证 任务名称
1 二维
2 3D
3 4D

Codes

身份证 代号 对于二维 对于3D 对于4D
1 二维 1 0 1
2 3D 0 1 1

为了添加列部分,我可以使用 Dapper 来处理。但是我如何编写查询并使用 Dapper 从表中提取数据并将其发送到前端?因为我不知道用户将在

Tasks
表中添加多少新行。

目前我有课

public class DqcDto
{
    public string? DqcCode { get; set; }
    public string? DqcDescription { get; set; }
    public string Project { get; set; }
    public bool? IsFor3D { get; set; }
    public bool? IsFor2D { get; set; }
}

但是当用户添加新列时不会使用此功能。

c# asp.net-core-webapi dynamic-programming dapper
1个回答
0
投票

您可以尝试下面的代码来查询数据库并使用 dapper 获取动态结果:

using Dapper;
using System.Data.SqlClient;
using System.Dynamic;
using System.Text.Json;


var connectionString = "ConnectionString";
var query = "SELECT * FROM Codes";

using (var connection = new SqlConnection(connectionString))
{
    var dynamicResults = connection.Query<dynamic>(query).ToList();
    foreach (var row in dynamicResults)
    {
        foreach (var property in (IDictionary<string, object>)row)
        {
            Console.WriteLine($"{property.Key}: {property.Value}");
        }
    }
    
    var json = JsonSerializer.Serialize(dynamicResults);
Console.WriteLine(json);// send `json` to the frontend

}

此代码将帮助查询

Codes
表中的所有列并迭代每一行,将其视为动态对象。

© www.soinside.com 2019 - 2024. All rights reserved.