Dapper Dot Net을 사용하여 데이터베이스 결과에서 Dictionary 개체에 매핑하는 방법은 무엇입니까?
다음과 같은 간단한 쿼리가있는 경우 :
string sql = "SELECT UniqueString, ID FROM Table";
다음과 같은 사전 객체에 매핑하고 싶습니다.
Dictionary<string, int> myDictionary = new Dictionary<string, int>();
Dapper로 어떻게할까요?
나는 그것이 다음과 같다고 가정합니다.
myDictionary = conn.Query<string, int>(sql, new { }).ToDictionary();
그러나 적절한 구문을 알아낼 수 없습니다.
이미 여러 가지 방법이 있습니다. 개인적으로 나는 비 제네릭 API를 사용합니다.
var dict = conn.Query(sql, args).ToDictionary(
row => (string)row.UniqueString,
row => (int)row.Id);
추가 수업 없이도 작동합니다.
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);
참고 : Dapper.NET 3.5 버전을 사용하는 경우 .NET 4.0 및 .NET 4.5 버전은 선택적 인수를 활용하므로 첫 번째, 두 번째 및 반환 유형을 사용하는 Query 메서드를 사용하려면 더 많은 매개 변수를 지정해야합니다 .
이 경우 다음 코드가 작동합니다.
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);
대부분의 인수는 기본값으로 되돌 리지만 splitOn
, 그렇지 않으면 기본값 인 'id'로 설정되므로 필수입니다.
반환 두 개의 열 '하는 쿼리 ID '와 ' 설명 ', splitOn
'로 설정해야합니다 설명 '.
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);
별칭과 강력한 유형을 사용할 수 있습니다.
별칭은 KeyValuePair 유형 Key 및 Value의 속성과 일치하는 키 포인트입니다.
강력한 타이핑에서 작동하며 잘 실행됩니다.
나는 동적 유형을 좋아하지 않는다. 특정 상황에서 재앙을 가져옵니다. 또한 boxing 및 unboxing은 성능 손실을 가져옵니다.
당신이하려는 일이 가능한지 잘 모르겠습니다. 쿼리를 매핑하기 위해 클래스를 정의하면 훨씬 간단 해집니다.
public class MyRow
{
public int Id { get; set; }
public string UniqueString { get; set; }
}
그런 다음 다음을 수행합니다.
var sql = "SELECT UniqueString, ID FROM Table";
var myDictionary = conn.Query<MyRow>(sql).ToDictionary(row => row.UniqueString, row => row.Id);
Dapper에는 ExecuteReader
. 따라서 다음과 같이 할 수도 있습니다.
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)
.
If you are using > .net 4.7 or netstandard2 you can use value tuples. 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);
ReferenceURL : https://stackoverflow.com/questions/14780767/how-to-map-to-a-dictionary-object-from-database-results-using-dapper-dot-net
'Development Tip' 카테고리의 다른 글
Java 컬렉션과 컬렉션의 차이점 (0) | 2021.01.05 |
---|---|
가능한 모든 방법으로 목록을 쌍으로 나누는 방법 (0) | 2021.01.05 |
PHPUnit : assertInstanceOf ()가 작동하지 않습니다. (0) | 2021.01.05 |
AWS 오류-Sudo : 호스트 IP-10-0-xx-xx를 해결할 수 없음 (0) | 2021.01.05 |
Http StaticInjectorError에 대한 공급자가 없습니다. (0) | 2021.01.05 |