0

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.

2
  • 2
    Could you show us an attempt where you got furthest in your opinion? Otherwise this question seems to be, can you do it for me. Commented Mar 24, 2015 at 11:44
  • I have been trying to resolve this since yesterday. My brain is fried and my attempts are no longer in ctrl z or ctrl y. Next time I shall save all my attempts as there seems to be people that would say do it for me here but I am not one of those. Commented Mar 24, 2015 at 12:15

1 Answer 1

1

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() 
             };
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks Getting 'object' does not contain a definition for 'InsertDate' from the view. I am passing the results via a ViewBag.
Why? You don't have InsertDate property in LogIns type?
Thought I Did 'public partial class LogIn { public int ID { get; set; } public Nullable<System.DateTime> InsertDate { get; set; } public string IP { get; set; } public string CertificateNumber { get; set; } }'
Okay, Just read your comment properly, since you are passing it via ViewBag, you can't access it directly. You need to type-cast it like this:- IEnumerable<LogIn> LogIns = (IEnumerable<LogIn)ViewBag.LogIn;
I appreciate your help and excuse my ignorance but am getting lost. I am attempting to return the results of the query to a list in the view. Where does the line above go, I tried it in the controller and the view.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.