Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean inside of Select()

I have a person table filled with Person information. I would like to get a list of the personer inside the table and check if they have renewed thier password in last 24 hours, and then return a person name and a boolean property whether they have updated the password or not.

This is my Person table:

Person table:

varchar(30) Name,
DateTime LastRenewedPassword.

Code:

public class Person
{
     public string Name { get; set; }
     public boolean HasRenewedPassword { get; set; }
}

public List<Person> GetPersons()
{
    using(var context = Entities())
    {
        var persons = from p in contex.Persons
                      select new Person
                      {
                          Name = p.Name,
                          HasRenewedPassword = // Has the personer renewed the password   for the last 24 hours?
                      }
    }
}

So my question is how can I, inside of select new {...} return if the personer have renewed the password or not?

All help is appriciated! And I´m open for any other suggestions for solution to this problem.

like image 767
Erik Larsson Avatar asked Oct 10 '11 14:10

Erik Larsson


1 Answers

Sounds like you want something like:

// As noted in comments, there are serious problems with this approach
// unless you store everything in UTC (or local time with offset).
DateTime renewalCutoff = DateTime.UtcNow.AddHours(-24);

using(var context = Entities())
{
    var persons = from p in context.Persons
                  select new Person
                  {
                      Name = p.Name,
                      HasRenewedPassword = p.LastRenewedPassword > renewalCutoff
                  };
}

(By evaluating DateTime.Now once and at the client side, it's likely to be easier to debug what's going on at any time - you can log that query parameter, for example.)

Note that as you're only doing a projection, you can simplify your code a bit:

var persons = context.Persons.Select(p => new Person {
                  Name = p.Name,
                  HasRenewedPassword = p.LastRenewedPassword > renewalCutoff
              });
like image 57
Jon Skeet Avatar answered Sep 25 '22 15:09

Jon Skeet