Search code examples
c#sqlleft-joindapperdto

Dapper - Map join query to DTO using 'splitOn'


How do you map a query with Dapper to your DTO class in relation to another DTO class?

Having this DTO class structure :

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; }
}

This is my query with some JOIN's :

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]

I'm trying to follow the example I found from the Dapper documentation website but no success so far.

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?");

Solution

  • Change your query to include the fields needed for the split

    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',
    

    so you can set them in the splitOn parameter

    ....
    splitOn: "b_id, c_id, d_id");