如何使用Dapper自动将剩余的列映射到字典? [英] How to use Dapper to automatically map remaining columns to dictionary?

查看:67
本文介绍了如何使用Dapper自动将剩余的列映射到字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Dapper映射到我的DTO:

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

我可以有一个 MyDto 实例根据约定填充前两个属性,但是我不确定如何告诉Dapper将所有剩余的列映射到字典中.

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

推荐答案

将查询作为动态对象返回.

var query = connection.Query<dynamic>(
    "Get_Something", commandType: CommandType.StoredProcedure, param: parameters);

然后,像这样映射您的DTO:

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

参考
RouteValueDictionary类

这篇关于如何使用Dapper自动将剩余的列映射到字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆