小巧的多重映射结果

时间:2017-07-26 18:47:39

标签: dapper

我有两个班级

public class Customer
{
    public int CustomerId { get; set;}
    public string CustomerName { get; set; }
}

public class Order
{
    public int OrderId { get; set; }
    public int CustomerId { get; set; }       //BuyerCustomer
    public int CustomerSecondId { get; set; } //ReceiverCustomer
    public Customer BuyerCustomer { get; set; }
    public Customer ReceiverCustomer { get; set; }
}

这里我的查询看起来像是

SELECT a.*, b.*, c.* FROM dbo.PRODUCTS_ORDER a
INNER JOIN  dbo.CUSTOMER b ON a.CustomerId=b.CustomerId
INNER JOIN   dbo.CUSTOMER c ON a.CustomerSecondId=b.CustomerId

Dapper Implementation ..

     List<Order> order= null;
 order= (List<Order>)dapperconnection.Query<Order, Customer, Customer, Order>(sql,
                                (order, customer1,customer2) =>
                                {
                                    order.BuyerCustomer = customer1;
                                    order.ReceiverCustomer = customer2;
                                    return order;
                                }, splitOn: "CustomerId,CustomerSecondId ");

我得到的结果不完整,只有RecevierCustomer被填充,而BuyerCustomer根本不包含任何值。

看起来dapper很混乱,因为我在查询中使用了两次CustomerId。 是否有任何解决方法,而无需更改我的Customer类?

1 个答案:

答案 0 :(得分:0)

您的班级设计和Dapper查询存在一些问题。

  • Customer.CustomerName应为字符串
  • 我会从Order中删除CustomerId和CustomerSecondId。它们是多余的。您在客户中同时拥有两个ID。
  • 从Split中删除CustomerSecondId。

以下是工作测试:

public class Order
{
    public int OrderId { get; set; }
    public Customer BuyerCustomer { get; set; }
    public Customer ReceiverCustomer { get; set; }
}

public class Customer
{
    public int CustomerId { get; set; }
    public string CustomerName { get; set; }
}


[Test]
public void TestSplitMany()
{
    using (var conn = new SqlConnection(@"Data Source=.\sqlexpress;Integrated Security=true; Initial Catalog=foo"))
    {
        var result =
            conn.Query<Order, Customer, Customer, Order>(@"select OrderId = 1, CustomerId = 2, CustomerName = 'Jim', CustomerId = 3, CustomerName = 'Bob'",
                (order, buyer, receiver) =>
                {
                    order.BuyerCustomer = buyer;
                    order.ReceiverCustomer = receiver;
                    return order;
                }, splitOn: "CustomerId").First();

        Assert.That(result.BuyerCustomer.CustomerId == 2);
        Assert.That(result.ReceiverCustomer.CustomerId == 3);

        Assert.That(result.BuyerCustomer.CustomerName == "Jim");
        Assert.That(result.ReceiverCustomer.CustomerName == "Bob");
    }
}