tags:

views:

85

answers:

2

need help to accomplish this in linq.

I have 3 tables.

  1. Customers

  2. CustumerOrder

  3. OrderDetails

I need to list in one query all customers ( only if they have placed atleast one order) with all the orders for each customer only if order value is greated than 100.

Regards,

Harsh

A: 

Here's a guess based off some assumptions:

var result = 
    from customer in Customers.Where(a => a.CustomerOrder.Count > 0)
    from order in CustomerOrder.Where(a => a.OrderDetails.Sum(b => b.Price) > 100)
    select new
    {
        customer, 
        order.OrderDetails
    }
Sorax
A: 

I'd say you want something like this:

from c in Customers
where c.CustomerOrders.Any()
select new
{
  customer,
  Orders = 
    from co in c.CustomerOrders
    where co.TotalPrice > 100
    select co.OrderDetails
}

Or, if you don't have an "TotalPrice" column in the CustomerOrder table, replace the inner query with this:

Orders =
  from cp in c.CustomerOrders
  where co.OrderDetails.Sum (od => od.Price) > 100
  select co.OrderDetails

Edit: if you want to include customers only with at least one order with OrderTotalPrice more than 100, use a let statement:

from c in Customers
let highValueOrders = 
    from co in c.CustomerOrders
    where co.TotalPrice > 100
    select co.OrderDetails
where highValueOrders.Any()
select new
{
  customer,
  highValueOrders
}

You can add more conditions in a similar fashion.

Joe Albahari
Thanks a lot everyone. I really appreciate that quick response.But this query does not take into consideration the part that - Customer would be in the final list only if he has atleast one order with OrderTotalPrice more than 100.+ Actually I had few more conditions here for inclusion of Customer in final selection like - Select Customer only if it has atleast one order with Age > 30 if Customer is of type "Regular" customer or Age > 35 if Customer is of type "Rare".CustomerType is stored in CustomerDetails table.Please help me with this..Regards,Harshal
Harshal
Thanks a lot Joe.. Few Questions - 1. Can we call C# functions inside the LINQ query or Lambda Expression? I need this to calculate Age, in my database there is a Birthday field and i would need a Age to be calculated from this field 2. How can i get the list from above LINQ query, Now i need only Customers from the above Query having more number of rows woth Customer details. I am really confused here. Dont know how can i pass this to UI. Can I get something like Dictionary<Customer, List<CustomerDetails>>?
Harshal
YOu can't call your own functions inside lambda expressions that go through a L2S or EF pipeline. For a workaround, check out this: http://mathgeekcoder.blogspot.com/2008/07/advanced-domain-model-queries-using.html
Joe Albahari