public class A
{
public int Id { get; set; }
public string Name { get; set; }
public B Range { get; set; }
}
public class B
{
public DateTime Start { get; set; }
public DateTime End { get; set; }
}
I’m calling Stored Procedure GetRecordsForA
, which returns values of records from a single table, I’m using the following snippet:
var commandDefinition = new CommandDefinition(
commandText: "dbo.GetRecordsForA",
parameters: null,
transaction: transaction,
commandType: CommandType.StoredProcedure);
var results = await connection.QueryAsync<A>(commandDefinition);
When the query results are deserialized, the properties within the "Range" are always null.
I have verified that the column names in the query results match the property names in class B. I’ve tried using the [Column("ColumnName")]
attribute for each property on class B.
The Stored Procedure I’m calling for reference:
CREATE OR ALTER PROCEDURE [GetRecordsForA]
AS
BEGIN
SELECT
a.[Id],
a.[StartDate] AS [Start],
a.[EndDate] AS [End],
a.[Name]
FROM
[A] a
END
You need to tell Dapper how to map the data retrieved by the stored procedure inside the two objects.
The first thing to change is the stored procedure changing the field order
ALTER PROCEDURE [GetRecordsForA]
AS
BEGIN
SELECT
a.[Id],
a.[Name],
a.[StartDate] AS [Start],
a.[EndDate] AS [End]
FROM
[A] a
END
Next you need to use a different overload of QueryAsync, you need the one that accepts in input two objects of type A and type B and then return the object A with the Range property set from the B instance received. Finally you need to tell Dapper how to split the returned data in the two objects expected by the func
var commandDefinition = new CommandDefinition(
commandText: "dbo.GetRecordsForA",
parameters: null,
commandType: CommandType.StoredProcedure);
var results = await connection.QueryAsync<A, B, A>(commandDefinition,
((objA, objB) =>
{
objA.Range = objB;
return objA;
}), splitOn:"Start");