Question

I have a series of tables that are joined with Primary Key/Foreign Key relationships. I have a table of Transactions, and each Transaction references one and only one Product. Each product can exist in one and only one Category:


Categories        Products           Transactions
-------------     -------------      -----------------
CategoryId        ProductId          TransactionId
CategoryName      CategoryId         ProductId
                  ProductName       TransactionAmount
  

I'm just learning LinqToSql, and I've used lambda expressions to access the Products in each category (x => x.Products). But what I'm trying to do is access the Transactions table, specifically to get a sum of all transactions by category.

I'm sure I could do this by creating manual Joins in my Linq statement. But it doesn't seem like I should have to do this, since all of my tables are joined as PF/FK in the model.

Can anyone offer an example of how to get started?

Was it helpful?

Solution

Without trying to compile it, I think this will work the way you want. It assumes that you have the associations set up in the LINQ to SQL data context.

var transPerCategory = db.Categories
                         .Select( c => new {
                             Name = c.CategoryName,
                             Amount = c.Products
                                       .Sum( p => p.Transactions
                                                   .Sum( t => t.TransactionAmount )
                                           )
                          });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top