Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
630 views
in Technique[技术] by (71.8m points)

c# - How to use Dapper to automatically map remaining columns to dictionary?

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
question from:https://stackoverflow.com/questions/65863392/how-to-use-dapper-to-automatically-map-remaining-columns-to-dictionary

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...