简体   繁体   English

如何使用 Dapper 从数据库 map 到字典?

[英]How to map to a Dictionary from database using Dapper?

I have a class:我有一个 class:

public class TestClass
{
    public string value1 {get; set;}
    public string value2 {get; set;}
    public string value3 {get; set;}
    public string value4 {get; set;}
}

and the database:和数据库:


Database - Test

id    code    value1    value2    value3     value4
--    ----    ------    ------    ------     ------

1     1000    xxxxx     xxxxx     xxxxx      xxxxx
2     1000    yyyyy     .....     .....      .....
3     1000    yyyy3     .....     .....      .....
4     1000    yyyy4
5     2000    yyyy5
6     2000    yyyy6
7     3000    yyyy7
8     3000    yyyy8
9     4000    yyyy9
10    4000    y9999

This is gonna be 4 key and 4 list of TestClass.这将是 TestClass 的 4 个键和 4 个列表。 string is a code and rest is testClass list. string 是一个代码,rest 是 testClass 列表。

I wanna map this to this dictionary: If Code is a same add it into list of TestClass.我想要 map 这个字典:如果代码相同,请将其添加到 TestClass 列表中。

Dictionary<string, List<TestClass>> testDic = new Dictionary<string, List<TestClass>>();
testDic = conn.Query("SELECT * FROM Test").ToDictionary(x=> x.????) ;

How to do it?怎么做? I assume it is something like think but its not working?我认为它类似于认为但它不起作用?

It looks like you're trying to group by the code .看起来您正在尝试按code分组。 To do that, I would do something like:为此,我会做类似的事情:

public class TestClass
{
    public int Id {get;set;}
    public string Code {get;set;}
    public string Value1 {get; set;}
    public string Value2 {get; set;}
    public string Value3 {get; set;}
    public string Value4 {get; set;}
}
/// ...
testDic = conn.Query<TestClass>("SELECT * FROM Test").ToLookup(x=> x.Code);

The ToLookup here is standard LINQ which works a lot like a Dictionary<TKey, List<TValue>> , but inbuilt (it is essentially a lot like GroupBy , but intended to be accessed multiple times).这里的ToLookup是标准的 LINQ ,它的工作原理很像Dictionary<TKey, List<TValue>> ,但是是内置的(它本质上很像GroupBy ,但打算被多次访问)。

If you actually need a dictionary, it is more complex;如果你真的需要字典,那就更复杂了; ToDictionary won't really help you, so the most practical approach is probably: ToDictionary不会真正帮助你,所以最实用的方法可能是:

var data = new Dictionary<string, List<TestClass>>();
foreach (var row in conn.Query<TestClass>("SELECT * FROM Test"))
{
    if (!data.TryGetValue(row.Code, out var list))
    {
        data.Add(row.Code, list = new List<TestClass>());
    }
    list.Add(row);
}

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

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