Linq query across three levels of tables to genera

2019-07-03 22:09发布

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?

1条回答
贪生不怕死
2楼-- · 2019-07-03 22:53

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 )
                                           )
                          });
查看更多
登录 后发表回答