ASP.net.MVC 5 create a page which will display sql query

Multi tool use
ASP.net.MVC 5 create a page which will display sql query
I want to learn how can I add to my controller some SQL query but I don't know how to do it properly.
My controller is
public ActionResult Index()
{
return View(db.Student.ToList());
}
By default page is giving me the next data.
ID, NAME, STATUS
1 Bella, 5
2 Bella, 5
3 Bella, 7
I want to add the next SQL query to the controller which will give me data that I want it on page to display.
(select distinct id,name,max(status) from students group by id,name)
ID, NAME, STATUS
3 Bella, 7
I first example 3 rows i want only one row which with max(status). So my page will display to users only one row
– white fang
Jul 3 at 8:17
2 Answers
2
I suggest you use a linq with a group-by clause as below;
var students = from s in db.Student
group s by s.name into groupedResult
select new
{
Name = groupedResult.Key,
Max_Status = groupedResult.Max(g => g.Status)
} ;
i did next var students = from s in db.Univet group s by s.Name into groupedResult select new { Name = groupedResult.Key, Max_Status = groupedResult.Max(g => g.Status) }; return View();
– white fang
Jul 3 at 8:58
Is the problem solved? Or does it still persist?
– Christian Nwafor
Jul 3 at 10:26
yes it working thank you, but where i need to add "Dinstinct" to avoid values which is repeatedly inserted to table
– white fang
Jul 3 at 10:47
like in my sql query
– white fang
Jul 3 at 10:47
is it correct return which i'm using ? " return View(db.Univet.ToList()); "
– white fang
Jul 3 at 10:57
If you want to group data by Name
and display Maximum value of Status
with linq then you can do as below.
Name
Status
var students = db.Student.GroupBy(i => i.Name)
.Select(g => new Student()
{
Name = g.Key,
Status = g.Max(row => row.Status),
Id = g.Max(row => row.Id)
}).ToList();
return View(students);
Name = g.Key - What does it mean ?
– white fang
Jul 3 at 8:41
I have added this to controller doest work (
– white fang
Jul 3 at 8:42
Name = g.Key
this will give you value of Name
property on which GroupBy is performed.– Karan
Jul 3 at 8:43
Name = g.Key
Name
should i change something in my cshtml code ?
– white fang
Jul 3 at 8:58
No. It should work fine.
– Karan
Jul 3 at 9:21
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
I'm not sure if I understand correctly, do you want to filter your data?
– OmarMuscatello
Jul 3 at 8:12