scottrakes
scottrakes

Reputation: 735

Linq Max with Default Value

I am trying to get the user's last login date and if no login records exist, return today's date. I am need some help getting there. I am getting the following error and do not even have the default value component.

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.DateTime?'

DateTime? logdate = from userlog in
                                    (from userlog in db.UserLogEntities
                                     where
                                       userlog.UserID == 1 &&
                                       userlog.Action == "Logon" &&
                                       userlog.ActionTag == "Success"
                                     select new
                                     {
                                         userlog.LogDate,
                                         Dummy = "x"
                                     })
                                group userlog by new { userlog.Dummy } into g
                                select new
                                {
                                    Column1 = (DateTime?)g.Max(p => p.LogDate)
                                };

Upvotes: 1

Views: 4143

Answers (3)

Arion
Arion

Reputation: 31239

That is also a doable solution. But you can also use. This solution so then you do not need an aggregate function.

var user= (
        from ul in db.UserLogEntities
         where ul.UserID == u.UserID &&
            ul.Action == "Logon" &&
            ul.ActionTag == "Success"
        orderby ul.LogDate descending
         select ul.LogDate??DateTime.Now ).FirstOrDefault();

Upvotes: 1

scottrakes
scottrakes

Reputation: 735

Below is what I came up with. Let me know if there is a better way.

LastLogin = (from ul in db.UserLogEntities
                                 where ul.UserID == u.UserID &&
                                    ul.Action == "Logon" &&
                                    ul.ActionTag == "Success"
                                 select ul.LogDate).DefaultIfEmpty(DateTime.Now).Max()

Upvotes: 8

Arion
Arion

Reputation: 31239

This is because you have selected a list of the dates. You should use FirstOrDefault() or SingleOrDefault() at the end of your query like this

select new
                                {
                                    Column1 = (DateTime?)g.Max(p => p.LogDate)
                                }.FirstOrDefault();

Or

select new
                                    {
                                        Column1 = (DateTime?)g.Max(p => p.LogDate)
                                    }.SingleOrDefault();

Upvotes: 0

Related Questions