[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.HarvestDate ";
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);
}
I want to rewrite the above code in LINQ. My requirement is to write LINQ query to fetch data from both tables.
House table
Id | Item | Qty |
---|---|---|
1 | Apple | 15.00 |
2 | Orange | 17.00 |
3 | Carrot | 8.00 |
Cart table
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 |
This is what l have tried
IEnumerable DataSource = (from c in _context.Cart join h in _context.House on c.Id equals h.Id select t1).ToList();
Expected output table
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 |