我有两个表,订单和客户,订单引用客户及其映射类订单和客户。
我想写一个方法,它接收订单和客户的Linq Where()条件:
void ProcessOrders(Expression<Func<Order, bool>> orderCondition,
Expression<Func<Customer, bool>> customerCondition)
{
var q = Database.Query<Order>().Where(orderCondition);
q = q.Where(o => o.Customer APPLY customerCondition); // how ?
... process records in q ...
}
即使在MSDN上阅读了关于此主题和相关文章的大量SO答案之后,我似乎无法弄清楚如何在Order.Customer属性上应用客户条件。
(正在使用的DB / ORM是Oracle / DevExpress,但我对通用解决方案很好,所以我没有将它们包含在标签中。请提及您的答案是否仅限于特定的数据库或ORM)
答案 0 :(得分:0)
这是实现它的一种方法。
void ProcessOrders(Expression<Func<Order, bool>> orderCondition,
Expression<Func<Customer, bool>> customerCondition>>)
{
var orders = Database.Query<Order>().Where(orderCondition);
var customers = Database.Query<Customer>().Where(customerCondition);
var q = from o in orders join c in customers on o.CustomerId == c.Id
select new {o, c}
}
同样,根据ORM,这样的事情也可能有效(我假设这里有一个延迟加载的Customer.Orders集合属性):
void ProcessOrders(Expression<Func<Order, bool>> orderCondition,
Expression<Func<Customer, bool>> customerCondition>>)
{
var customers = Database.Query<Customer>().Where(customerCondition);
var q = from c in customers
let orders = c.Orders.Where(orderCondition)
select new {c, orders}
}
任何解决方案都必须针对特定的linq提供商进行测试,因为不同的linq提供商可能支持或不支持某些查询......
答案 1 :(得分:0)
您可以尝试这样的事情:
var q = (from o in Database.Query<Order>().Where(orderCondition)
join c in Database.Query<Customer>().Where(customerCondition) on o.CustomerID equals c.CustomerID
select new { Order = o, Customer = c });