如何使用结果映射将dapper结果转化为字典

问题描述 投票:1回答:1

我想使用这里表示的splitOn功能。https:/dapper-tutorial.netresult-multi-mapping。

将结果中的每个Order分组为一个整数属性 "EmployeeId"。我遵循了来自 如何使用Dapper Dot Net从数据库结果映射到Dictionary对象?

但我得到的是 An item with the same key has already been added. 那么,我怎样才能按EmployeeId对我的订单进行分组呢?

我不能修改 Order 类,而我更喜欢使用一个字典,而不是创建一个包装Order的类。然而,如果没有其他的方法,我愿意接受封装Order

https:/dotnetfiddle.nethn6Sjf

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);              
        }
    }
}
c# sql-server dictionary dapper
1个回答
1
投票

这能满足你的需求吗?

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

摆弄


0
投票

你可以创建一个信封类(如果你喜欢,也可以使用动态类)。

public class OrderEntity
{
  public int EmployeeID {get;set;}
  public Order Order {get;set;}
}

然后将结果集映射到按雇员id分组的字典中,这就很简单了。

var dict = new Dictionary<int,List<Order>>();
var r = connection.Query<OrderEntity, Order, OrderEntity>(sql,(orderEntity, order) => 
    {
        // You can skip that line if you want, the orderEntity is (probably) never used.
        orderEntity.Order = order;

        if(dict.ContainsKey(orderEntity.EmployeeID))
        {
            dict[orderEntity.EmployeeID].Add(orderEntity.Order);
        }
        else
        {
            dict.Add(orderEntity.EmployeeID, new List<Order> {orderEntity.Order});
        }

        return orderEntity;
    }, splitOn: "OrderID");

这个方法只需要对结果集进行1次迭代,并且只需要对字典进行O(1)键查找。

© www.soinside.com 2019 - 2024. All rights reserved.