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

早过忘川 提交于 2020-01-17 08:14:04

问题


I have two tables: Customer and Orders. The customer has a reference to Orders like such:

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

The Order class has an attribute Deleted. I'd like to load all Customers (or a subset), and include the Orders, but not the ones with Deleted=true. Can this be done with LoadSelect methods, or what is the recommended way?

Something that would roughly equal the following SQL:

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

Is this the best way?

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

回答1:


I've just added a new Merge API in this commit to automatically join a parent collection with their child references that will make this a little easier.

With the new API you can select customers and orders separately and merge the collections together, e.g:

//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

This change is available from v4.0.39+ that's now available on MyGet.



来源:https://stackoverflow.com/questions/29103559/how-to-set-conditions-filters-on-references-when-using-load-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!