问题
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