如何使用 Dapper 将查询映射到与另一个 DTO 类相关的 DTO 类?
拥有这个 DTO 类结构:
public class ClassA
{
public string AField1 { get; set; }
public string AField2 { get; set; }
public string AField3 { get; set; }
public ClassB ClassB { get; set; }
}
public class ClassB
{
public string BField1 { get; set; }
public string BField2 { get; set; }
public ClassC ClassC { get; set; }
}
public class ClassC
{
public string CField1 { get; set; }
public string CField2 { get; set; }
}
这是我对一些 JOIN 的查询:
SELECT
[a].[a_field_1] AS 'AField1',
[a].[a_field_2] AS 'AField2',
[a].[a_field_3] AS 'AField3',
[b].[b_field_1] AS 'BField1',
[b].[b_field_2] AS 'BField2',
[c].[c_field_1] AS 'CField1',
[c].[c_field_2] AS 'CField2',
[d].[d_field_1] AS 'DField1',
FROM
[dbo].[Table_A] AS [a]
LEFT JOIN
[dbo].[Table_B] AS [b] ON [a].[table_a_id] = [b].[a_id]
LEFT JOIN
[dbo].[Table_C] AS [c] ON [b].[table_b_id] = [c].[b_id]
LEFT JOIN
[dbo].[Table_D] AS [d] ON [c].[table_c_id] = [d].[c_id]
LEFT JOIN
[dbo].[Table_E] AS [e] ON [d].[table_d_id] = [e].[d_id]
我正在尝试遵循从 Dapper 文档网站找到的示例,但到目前为止尚未成功。
var query = await sqlConnection.QueryAsync<ClassA, ClassB, ClassC> (SqlStatementHelper.ReadSqlStatementFile(SqlStatementFileNames.MyQuery), (classA, classB,
classC) =>
{
classA.ClassB = classB;
classB.ClassC = classC;
return classA;
},
splitOn: "Split on what?");
split_on
using var query = await sqlConnection.QueryAsync<ClassA, ClassB, ClassC> (SqlStatementHelper.ReadSqlStatementFile(SqlStatementFileNames.MyQuery), (classA, classB,
classC) =>
{
classA.ClassB = classB;
classB.ClassC = classC;
return classA;
},
splitOn: "BField1,CField1");
更改您的查询以包含拆分所需的字段
SELECT
[a].[a_field_1] AS 'AField1',
[a].[a_field_2] AS 'AField2',
[a].[a_field_3] AS 'AField3',
[b].[b_id],
[b].[b_field_1] AS 'BField1',
[b].[b_field_2] AS 'BField2',
[c].]c_id],
[c].[c_field_1] AS 'CField1',
[c].[c_field_2] AS 'CField2',
[d].[d_id],
[d].[d_field_1] AS 'DField1',
所以你可以在 splitOn 参数中设置它们
....
splitOn: "b_id, c_id, d_id");