views:

41

answers:

1

I'm a bit stuck on the following linq query. I'm trying to find all orders which have a state other than "Completed", or which have been completed within the last month.

_ordersRepository.GetAllByFilter(
     o => o.OrderStatus
         .OrderByDescending(os => os.StatusUpdate.Date)
         .First() 

          // so at this point I have found the most recent status,
          // and I need to do something like...

          /* pseudo code */
          WHERE
              StatusUpdate.StatusType.Name != "Completed" 
          OR
              StatusUpdate.Date > DateTime.Today.AddMonths(-1)
    );

EDIT to clarify: The difficulty I'm having is that I don't have a direct way to get the current status like Order.Status. The status is kept historically in a StatusUpdate table. A StatusUpdate is connected to an Order by an OrderStatus linker table (one Order has many StatusUpdates). So if you look at my attempted code above, you see I am finding out the current status with:

Order.OrderStatus.OrderByDescending(os => os.StatusUpdate.Date).First()

This gives me a StatusUpdate corresponding to the current order status. I now need to check:

StatusUpdate.StatusType.Name == "Completed" // StatusType is like an enum lookup table
OR
StatusUpdate.Date > lastMonth 

I can almost get how I could do it, but not without being horribly inefficient.

+1  A: 

I think I got it now. It's like I do it in my apps, I have Statuses, Orders and "Movements" table where the last one is the current. Updating my example.

DateTime dateToMatch = DateTime.Today.AddMonths(-1);
var orders = from c in Context.Orders
let currentMovement == c.Movements.OrderByDescending(x => x.PerformedOn).FirstOrDefault()
let currentStatusName == currentMovement.Status.Name
where currentStatusName != "Completed" || (currentStatusName == "Completed" && currentMovement.PerformedOn > dateToMatch)
select c;
Matteo Mosca
Yes I think that gets what I need, thanks. I didn't know about "let". Only one problem though: my GetAllByFilter method on my repository takes a lambda parameter. Is it even possible to write this query in lambda syntax?
fearofawhackplanet