2017-07-26 64 views
0

我有两个类小巧玲珑多映射结果

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 

小巧玲珑实现..

 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根本不包含任何值。

由于我在查询中使用了两次CustomerId,所以它看起来像dapper一样困惑。 有没有任何解决方法,而不必改变我的客户类?

回答

0

您的课堂设计和Dapper查询几乎没有问题。

  • Customer.CustomerName应该是字符串
  • 我会从已删除客户ID和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"); 
    } 
} 
+0

哦,遗憾的错字。我修好了它。让我试着做一些测试。谢谢。 – Derstine

+0

为什么我需要从Split中删除CustomerSecondId?我真的不明白,因为我真的需要它的加入。 – Derstine

+0

CustomerSecondId是订单的一部分。当您查看SQL查询结果时,您有Order和Customer,Customer,那么我们只需按CustomerId划分两个客户记录。我将编辑最后一点。 –