How to use Dapper to automatically map remaining columns to dictionary?

馋奶兔 提交于 2021-02-08 10:30:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!