如何使用LINQ语句从两张表查询数据?SQL转LINQ实现
问题:将原生SQL聚合查询改写为LINQ
我有一段通过原生SQL实现Cart表左联House表聚合查询的ASP.NET Core接口代码,希望将其改写为LINQ查询。以下是相关表结构、数据、我尝试的不完整LINQ代码以及预期查询结果,需要完成正确的LINQ查询实现。
原原生SQL实现的接口代码
[Route("Mode")] [HttpGet] public object Mode() { string query = "Select Sum(c.total) as Total, Sum(h.Qty) as Qty, Sum(c.Amount) as Amount, Count(c.Item) as Count, " + "c.Item, c.Model, h.Date From Cart c Left Join House as h On c.Id = h.Id Group By c.Item, c.Model, h.Date "; DataTable dt = new DataTable(); string sqlDataSource = _configuration.GetConnectionString("DefaultConnection"); SqlDataReader dr; using (SqlConnection con = new SqlConnection(sqlDataSource)) { con.Open(); using (SqlCommand cmd = new SqlCommand(query, con)) { dr = cmd.ExecuteReader(); dt.Load(dr); dr.Close(); con.Close(); } } return new JsonResult(dt); }
House表结构及数据
| Id | Item | Qty |
|---|---|---|
| 1 | Apple | 15.00 |
| 2 | Orange | 17.00 |
| 3 | Carrot | 8.00 |
Cart表结构及数据
| CId | Item | Qty | Amount | Total | Id | Date |
|---|---|---|---|---|---|---|
| 1 | Apple | 2 | 2.00 | 4.00 | 1 | 04/07/2024 |
| 2 | Apple | 2 | 2.00 | 4.00 | 1 | 04/07/2024 |
| 3 | Orange | 5 | 3.00 | 15.00 | 2 | 05/07/2024 |
| 4 | Carrot | 4 | 2.00 | 8.00 | 3 | 11/07/2024 |
| 5 | Carrot | 2 | 2.00 | 4.00 | 3 | 11/07/2024 |
我尝试的不完整LINQ代码
IEnumerable DataSource = (from c in _context.Cart join h in _context.House on c.Id equals h.Id select t1).ToList();
预期输出结果
| Date | Item | Qty | Amount | Total | Count |
|---|---|---|---|---|---|
| 04/07/2024 | Apple | 2 | 2.00 | 8.00 | 2 |
| 05/07/2024 | Orange | 5 | 2.00 | 15.00 | 1 |
| 11/07/2024 | Carrot | 6 | 2.00 | 12.00 | 2 |
正确的LINQ实现
结合预期结果修正原SQL中的逻辑偏差(原SQL中Sum(h.Qty)与预期不符,实际应为聚合Cart表的Qty),同时实现左连接与分组聚合:
[Route("Mode")] [HttpGet] public IActionResult Mode() { var result = from c in _context.Cart // 左连接House表,确保Cart所有记录被保留 join h in _context.House on c.Id equals h.Id into houseGroup from h in houseGroup.DefaultIfEmpty() // 按Item和Date分组(原SQL的c.Model在Cart表中不存在,故忽略) group c by new { c.Item, c.Date } into grouped select new { grouped.Key.Date, grouped.Key.Item, Qty = grouped.Sum(x => x.Qty), Amount = grouped.Sum(x => x.Amount), Total = grouped.Sum(x => x.Total), Count = grouped.Count() }; return new JsonResult(result.ToList()); }
关键说明:
- 左连接实现:通过
join ... into配合DefaultIfEmpty()实现SQL的Left Join逻辑,保证Cart表无匹配House记录的条目也能被查询到。 - 分组逻辑:根据预期结果调整分组字段为
Item和Date,原SQL中的c.Model未在Cart表结构中出现,故移除该分组条件。 - 聚合计算:完全匹配预期结果的字段逻辑,分别计算Qty、Amount、Total的总和,以及分组内的记录数量。
内容的提问来源于stack exchange,提问作者Milie24
相关产品推荐
相关产品推荐

