使用Fluent语法将SQL查询转换为谓词表达式

时间:2014-01-28 17:26:08

标签: c# linq linq-to-sql

如何使用Fluent Sytax将以下sql查询写入Predicate Expression:

select c.* from customer c
inner join Orders r on r.CustomerId = c.Id
where
    c.MemberSince > '01/01/2013' &&
    r.OrderDate > '01/01/2014'
order by r.OrderDate

我期待这样的事情:

Expression<Func<Customer, bool>> filters = PredicateBuilder.True<Customer>();
filters = filters.And(x => x.MemberSince > DateTime.Parse('01/01/2013'));
filterr = ....

我不确定如何添加Orders谓词。然后我打电话给:

var list = db.Customers.AsExpandable().Where(filters).ToList();

1 个答案:

答案 0 :(得分:0)

根本不需要PredicateBuilder。您只需要了解连接的结果实际上是一对对的结果:

DateTime memberCutoff = ...;
DateTime orderCutoff = ...;
var query = context.Customers
                   .Join(context.Orders,
                         c => c.Id, r => r.CustomerId, (c, r) => new { c, r })
                   .Where(pair => pair.c.MemberSince > memberCutoff &&
                                  pair.r.OrderDate > orderCutoff)
                   .OrderBy(pair => pair.r.OrderDate);