I am trying to convert he following SQL statement to LINQ to use in an MVC Controller.
SELECT COUNT(*) AS LoginCount, InsertDate, CertificateNumber
FROM dbo.LogIns
GROUP BY InsertDate, CertificateNumber
I have made several attempts with no luck.
I am trying to convert he following SQL statement to LINQ to use in an MVC Controller.
SELECT COUNT(*) AS LoginCount, InsertDate, CertificateNumber
FROM dbo.LogIns
GROUP BY InsertDate, CertificateNumber
I have made several attempts with no luck.
Try this:-
var result = db.LogIns.GroupBy(x => new { x.InsertDate, x.CertificateNumber })
.Select(x => new
{
InsertDate = x.Key.InsertDate,
CertificateNumber = x.Key.CertificateNumber,
LoginCount = x.Count()
});
Or with query syntax:-
var result = from x in db.LogIns
group x by new { x.InsertDate, x.CertificateNumber } into g
select new
{
InsertDate = g.Key.InsertDate,
CertificateNumber = g.Key.CertificateNumber,
LoginCount = g.Count()
};
InsertDate property in LogIns type?ViewBag, you can't access it directly. You need to type-cast it like this:- IEnumerable<LogIn> LogIns = (IEnumerable<LogIn)ViewBag.LogIn;