2011-01-20 68 views
2

我有一个L2S存储库查询,我正忙着用一种很好的方式写。它看起来像...处理链式linq-to-sql查询表达式中的空值

_orderRepository 
    .GetAllByFilter(o => o.CustomerId == id) 
    .Select(o => 
     new CustomerOrderRecord 
     (
       o.Id, 
       o.PartNumber, 
       o.Date 
       // ... etc, more order details 

      /* Here I need the last DateTime? the customer placed 
       an order for this item, which might be null. 
       So I end up with the following horrible part of 
       the query */ 
       o.Customer.CustomerOrderRecords 
        .Where(x => x.PartNumber == o.PartNumber) 
        .OrderByDescending(x => x.Date).FirstOrDefault() 
        == null ? null : 
          o.Customer.CustomerOrderRecords 
          .Where(x => x.PartNumber == o.PartNumber) 
          .OrderByDescending(x => x.Date).First().Date; 

     )).ToList(); 

所以希望你能看到收到LastOrdered值当我在写整个查询链只是做两次空校验的问题。

这需要在线(我认为),因为GetAllByFilter返回IQueryable

我试图在select语句中使用一个中间变量,所以我有点像下面的东西,但我不能得到任何类似的东西来编译。

​​

是否有可用的语法技巧来解决这个问题?

回答

1

尝试使用Select,以获取Date成员:

o.Customer.CustomerOrderRecords 
    .Where(x => x.PartNumber == o.PartNumber) 
    .OrderByDescending(x => x.Date) 
    .Select(x => (DateTime?)x.Date) 
    .FirstOrDefault() 
+0

为什么我没有想到写这么认为的!?很简单!谢谢 :) – fearofawhackplanet 2011-01-20 13:03:02