简体   繁体   English

如何使用 Dapper Dot Net 从数据库结果映射到 Dictionary 对象?

[英]How to map to a Dictionary object from database results using Dapper Dot Net?

If I have a simple query such as:如果我有一个简单的查询,例如:

string sql = "SELECT UniqueString, ID  FROM Table";

and I want to map it to a dictionary object such as:我想将它映射到一个字典对象,例如:

Dictionary<string, int> myDictionary = new Dictionary<string, int>();      

How would I do this with Dapper?我将如何使用 Dapper 做到这一点?

I assume it is something like:我假设它是这样的:

myDictionary = conn.Query<string, int>(sql, new {  }).ToDictionary();

But can't figure out the proper syntax.但无法弄清楚正确的语法。

There's various ways already shown;已经展示了多种方式; personally I'd just use the non-generic api:我个人只是使​​用非通用api:

var dict = conn.Query(sql, args).ToDictionary(
    row => (string)row.UniqueString,
    row => (int)row.Id);
string strSql = "SELECT DISTINCT TableID AS [Key],TableName AS [Value] FROM dbo.TS_TStuctMaster";
Dictionary<string,string> dicts = sqlConnection.Query<KeyValuePair<string,string>>(strSql).ToDictionary(pair => pair.Key, pair => pair.Value);

You can use aliases and strong types.您可以使用别名和强类型。

Aliases are the key points, which match the attributes of KeyValuePair type Key and Value.别名是关键点,它匹配 KeyValuePair 类型 Key 和 Value 的属性。

It works under strong typing and runs well.它在强类型下工作并且运行良好。

I don't like dynamic type.我不喜欢动态类型。 It brings disaster in certain situations.它在某些情况下会带来灾难。 Moreover, the boxing and unboxing brings performance loss.而且,装箱和拆箱会带来性能损失。

Works also without an additional class:无需额外的类也可以工作:

var myDictionary = conn.Query<string, int, KeyValuePair<string,int>>(sql, (s,i) => new KeyValuePair<string, int>(s,i))
    .ToDictionary(kv => kv.Key, kv => kv.Value);

NOTE : When using Dapper.NET 3.5 version, the Query method that takes the first, second and return types requires you specify more parameters, as the .NET 4.0 and .NET 4.5 versions take advantage of optional arguments .注意:使用 Dapper.NET 3.5 版本时,采用第一个、第二个和返回类型的 Query 方法需要您指定更多参数,因为 .NET 4.0 和 .NET 4.5 版本利用了可选参数

In this case, the following code should work:在这种情况下,以下代码应该可以工作:

string splitOn = "TheNameOfTheValueColumn";
var myDictionary = conn.Query<string, int, KeyValuePair<string,int>>(sql, (s,i) => new KeyValuePair<string, int>(s,i), null, null, false, splitOn, null, null)
        .ToDictionary(kv => kv.Key, kv => kv.Value);

Most of the arguments will revert to a default, but splitOn is required, as it will otherwise default to a value of 'id'.大多数参数将恢复为默认值,但splitOn是必需的,否则它将默认为 'id' 值。

For a query that returns two columns, ' ID ' and ' Description ', splitOn should be set to ' Description '.对于返回两列“ ID ”和“说明”的查询, splitOn应设置为“说明”。

If you are using > .net 4.7 or netstandard2 you can use value tuples.如果您使用的是 > .net 4.7 或 netstandard2,您可以使用值元组。 the code is nice and terse and there is no use of dynamics.代码简洁明了,没有使用动态。

var sql = "SELECT UniqueString, Id  FROM Table";
var dict = conn.Query<(string UniqueString, int Id)>(sql)
           .ToDictionary(t => t.UniqueString,t => t.Id);

Dapper also has an extension method for ExecuteReader . Dapper 还有一个ExecuteReader的扩展方法。 So, you could also do this:所以,你也可以这样做:

var sql = "SELECT UniqueString, ID  FROM Table";
var rows = new List<Dictionary<string, int>>();
using (var reader = cn.ExecuteReader(sql)) {
    while (reader.Read()) {
        var dict = new Dictionary<string, int>();
        for (var i = 0; i < reader.FieldCount; i++) {
            dict[reader.GetName(i)] = reader.GetInt32(i);
        }
        rows.Add(dict);
    }
}

This approach works without knowing the column names.这种方法在不知道列名的情况下也能工作。 Moreover, if you don't know the data types, you could change Dictionary<string,int> to Dictionary<string,object> and GetInt32(i) to GetValue(i) .此外,如果您不知道数据类型,您可以将Dictionary<string,int>更改为Dictionary<string,object>并将GetInt32(i)更改为GetValue(i)

I'm not sure if what you're trying to do is possible.我不确定你想做的事情是否可行。 If you define a class to map the query to this becomes far more trivial:如果您定义一个类来将查询映射到这变得更加简单:

public class MyRow
{
    public int Id { get; set; }
    public string UniqueString { get; set; }
}

Then, you would just do this:然后,您只需执行以下操作:

var sql = "SELECT UniqueString, ID  FROM Table";
var myDictionary = conn.Query<MyRow>(sql).ToDictionary(row => row.UniqueString, row => row.Id);

For the table of which you do not know the structure at runtime对于在运行时不知道其结构的表

    using var db = new SqlConnection(_connectionString);
    var sql = $"Select * From {tableName} Order By {primaryKey}";

    var result = await db.QueryAsync(sql); 
    return result
        .Cast<IDictionary<string, object>>()
        .Select(it => it.ToDictionary(it => it.Key, it => it.Value));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM