views:

723

answers:

2

I have two tables Customers, Orders

Customers CustomerID FName LName

Orders OrderId CustomerID OrderDate

I want to make a linq statement that can join these two tables and get
FName, LName, Count of orders for each customer

+3  A: 
from c in Customers
join o in Orders on c.CustomerID equals o.CustomerID into g
select new { c.FName, c.LName, Count=g.Count() }
Winston Smith
+1  A: 
from c in db.Customers
let theCount = c.Orders.Count()
select new {c.FName, c.LName, theCount}

http://msdn.microsoft.com/en-us/library/bb425822.aspx#linqtosql_topic11

These access operations translate to more complicated joins or correlated sub-queries in the equivalent SQL, allowing you to walk through your object graph during a query.

David B
This assumes a linq-to-objects type of relationship where a Customer object contains a List of Orders
Winston Smith
LinqToSql can model this relationship. This evaluations is done 100% in the database.
David B
Does this assume the relationships are set up correctly in the database with Orders having an FK to Customers? Otherwise how would it know what c.Orders is?
Winston Smith
Doesn't matter if the FK is set in the database, just add the relationship in the LinqToSql designer.
David B