问题
I am attempting to use Dapper to map to my DTO:
public class MyDto
{
public int Id { get; set; }
public string Code { get; set; }
public IDictionary<string, object> AdditionalColumns { get; set; }
}
I can have an instance of MyDto
populate the first two properties based on convention, but I'm not sure how to tell Dapper to map all remaining columns into the dictionary.
connection.Query<MyDto>("Get_Something", commandType: CommandType.StoredProcedure, param: parameters);
The stored procedure returns the following:
Id: INT
Code: VARCHAR(32)
Foo: VARCHAR(16)
Bar: DATETIME
回答1:
Return your query as dynamic
objects.
var query = connection.Query<dynamic>(
"Get_Something", commandType: CommandType.StoredProcedure, param: parameters);
Then, map your DTO's like this:
var results = new List<MyDto>();
foreach(item in query)
{
var dictionary = new RouteValueDictionary(item).ToDictionary(x => x.Key, y => y.Value);
var dto = new MyDto
{
Id = dictionary["Id"];
Code = dictionary["Code"];
}
dictionary.Remove("Id");
dictionary.Remove("Code");
dto.AdditionalColumns = dictionary;
results.Add(dto)
}
Reference
RouteValueDictionary Class
来源:https://stackoverflow.com/questions/60839565/map-leftover-column-names-to-populate-a-dictionary-in-dapper-net