简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM