Search code examples
databaselinqclientorders

Retrieve inactive clients by LINQ


I have a problem with my code. I want to retrieve all the inactive clients(that have no orders) from last week. This is my information from database. information in database picture Below is my code in LINQ, but it does not return anything.

DateTime daysBeforeToday = DateTime.Today.AddDays(-7);
var queryCount = context.Orders.Select(x=>x.ID).Count();
var query = (from o in context.Orders
where o.OrderDate >= daysBeforeToday
select new { CustomerName = o.CustomerName, ID = o.ID } into Customers
group Customers by Customers.CustomerName into pg
where queryCount == 0
select pg.Key);
return query.ToList();

Please advice. Thank you

UPDATE
I found this SQL statement that works:

SELECT CustomerName, MAX(OrderDate) as LastOrderDate
FROM Orders 
GROUP By CustomerName
having MAX(OrderDate) < dateAdd(day,-7, GetDate())

but when I convert in LINQ it fails. What I did wrong?

DateTime daysBeforeToday = DateTime.Today.AddDays(-7);
var queryMax = context.Orders.Select(x=>x.OrderDate).Max();

var query = (from o in context.Orders
            select new { CustomerName = o.CustomerName, Date = o.OrderDate } into Customers
            group Customers by Customers.CustomerName into pg
            where queryMax < daysBeforeToday
            select pg.Key);

return query.ToList();

Solution

  • Like the comment, The Max should be calculated for each grouped customer, like the following code:

    DateTime daysBeforeToday = DateTime.Today.AddDays(-7);
    
    var query = (from o in context.Orders           
                group o by o.CustomerName into pg
                where pg.Max(x => x.OrderDate) < daysBeforeToday
                select pg.Key);
    
    return query.ToList();
    

    I hope you find this helpful.