gpt4 book ai didi

c# - 如何使用结果映射将 dapper 结果转换为字典

转载 作者:行者123 更新时间:2023-12-03 20:54:03 25 4
gpt4 key购买 nike

我想使用此处表示的 splitOn 功能:https://dapper-tutorial.net/result-multi-mapping

将结果的每个 Order 分组到一个整数属性“EmployeeId”。我听从了 How to map to a Dictionary object from database results using Dapper Dot Net? 的建议

但我收到了 An item with the same key has already been added.那么如何按 EmployeeId 对我的订单进行分组?

我无法修改 Order class 并且我更喜欢使用字典而不是创建一个包装 Order 的类。但是,如果没有其他方法,我对包装 Order 的想法持开放态度

https://dotnetfiddle.net/hn6Sjf

public class Program
{
public class Order
{
public int OrderID { get; set; }
public int CustomerID { get; set; }
public DateTime OrderDate { get; set; }
public int ShipperID { get; set; }
}

public static void Main()
{
string sql = @"
SELECT TOP 10
EmployeeID,
OrderID,
CustomerID,
OrderDate,
ShipperID
FROM Orders
ORDER BY OrderID;
";

using (var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServerW3Schools()))
{
var rawList = connection.Query<Order>(sql);
FiddleHelper.WriteTable(rawList);


var dict = connection.Query<int, List<Order>, KeyValuePair<int, List<Order>>>(sql,
(s, i) => new KeyValuePair<int, List<Order>>(s, i), null, null, true, "OrderID")
.ToDictionary(kv => kv.Key, kv => kv.Value);

FiddleHelper.WriteTable(dict);
}
}
}

最佳答案

这会满足您的需求吗?

var dict = connection.Query<int, Order, ValueTuple<int, Order>>(sql,
(s, i) => ValueTuple.Create(s, i), null, null, true, "OrderID")
.GroupBy(t => t.Item1, t => t.Item2, (k, v) => new {Key = k, List = v})
.ToDictionary(kv => kv.Key, kv => kv.List);

Fiddle

关于c# - 如何使用结果映射将 dapper 结果转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61551786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com