小巧的一对多在许多人中失去了身份

时间:2012-02-27 14:21:44

标签: dapper

给出以下两个实体

public class Customer
{
    public Customer()
    {
        Orders = new List<Orders>();
    }

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

    public List<Orders> Orders { get; set; }
}

public class Orders
{
    public int OrderId { get; set; }
    public int CustomerId { get; set; }
    public int Quantity { get; set; }
    public string OrderDescription { get; set; }
}

以下代码

string sql = @"
select c.CustomerId, c.CustomerName, o.OrderId as OrderId, o.CustomerId, o.Quantity, o.OrderDescription 
from Customer c 
join Orders o on c.CustomerId = o.CustomerId";

var customers = new List<Customer>();
Customer currentCustomer = null;
var c = connection.Query<Customer, Orders, Customer>(
    sql, (customer, order) => {
        if (currentCustomer == null || currentCustomer.CustomerId != customer.CustomerId) 
        {
            customers.Add(customer);
            currentCustomer = customer;
        }
        currentCustomer.Orders.Add(order);
        return currentCustomer;
    }, splitOn: "CustomerId, OrderId");

当我检查客户时,OrderId始终为0.如在customers.Orders [0] .OrderId为零,对于所有客户。现在我想是我做错了什么,但我无法弄清楚是什么。您在上面看到的奇怪的SQL是我尝试强制OrderId工作的尝试。

0 个答案:

没有答案