使用 Load* 方法时如何在引用上设置 conditions/filters

How to set conditions/filters on references when using Load* methods

我有两个表:客户和订单。客户有这样的订单参考:

[Reference]
public List<Order> Orders { get; set; }

订单 class 具有属性 Deleted。我想加载所有客户(或子集),并包括订单,但不包括 Deleted=true 的订单。这可以用 LoadSelect 方法完成吗,或者推荐的方法是什么?

大致等于以下 SQL:

select * from Customers C 
join Orders O on O.CustomerId = C.Id 
where O.Deleted = False

这是最好的方法吗?

var orderIds = resp.Customers.Select(q => q.Id).ToList();
var allOrders = Db.Select<Order>(o => orderIds.Contains(o.CustomerId) && !o.Deleted);
foreach (var order in allOrders)
{
    var cust = resp.Customers.First(q => q.Id == order.custivityId);
    if (cust.Orders == null) cust.Orders = new List<Order>();
    cust.Orders.Add(order);
}

我刚刚添加了一个新的 Merge API in this commit 来自动加入父集合及其子引用,这将使这更容易一些。

使用新的 API,您可以 select 客户和订单分开并将集合合并在一起,例如:

//Select only Customers which have valid orders
var customers = db.Select<Customer>(q =>
    q.Join<Order>()
     .Where<Order>(o => o.Deleted == false)
     .SelectDistinct());

//Select valid orders
var orders = db.Select<Order>(o => o.Deleted == false);

customers.Merge(orders); //merge the results together

customers.PrintDump();   //print the results of the merged collection

此更改适用于 v4.0.39+,现在是 available on MyGet