开发者

Dealing with null values in chained linq-to-sql query expressions

I have a L2S repository query which I'm stuggling to write in a nice way. It looks something like...

_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();

So hopefully you can see the problem that I'm having to write the whole query chain 开发者_如何转开发twice just to do the null check when receiving the LastOrdered value.

This needs to be written in-line (I think) because GetAllByFilter returns an IQueryable.

I tried to use an intermediate variable within the select statement, so I'd have something a bit like the following, but I couldn't get anything like that to compile.

.Select(o => 
         new CustomerOrderRecord
         (
              o.Id,
              o.PartNumber,
              o.Date
              // ... etc, more order details

              var last = o.Customer.CustomerOrderRecords
                    .Where(x => x.PartNumber == o.PartNumber)
                    .OrderByDescending(x => x.Date).FirstOrDefault()
                    == null ? null : last.Date;

          )).ToList();

Is there a syntax trick available which solves this problem?


Try using Select to fetch the Date member:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜