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?
开发者_如何学C }
}
}
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.
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
});
Well, I'm guessing something like:
var cutoff = DateTime.Now.AddDays(-1);
...
select new Person
{
Name = p.Name,
HasRenewedPassword = p.PasswordChanged >= cutoff
}
Try
select new Person
{
Name = p.Name,
HasRenewedPassword = (DateTime.Now - p.LastRenewedPassword).TotalHours <= 24
}
You can use a TimeSpan:
HasRenewedPassword = (DateTime.Now - p.LastRenewedPassword).TotalHours <= 24
var renewalTime = DateTime.Now.Substract(new TimeSpan(24,0,0));
// insert in the select code
HasRenewedPassword = p.LastRenewedPassword > renewalTime
You can set this value by adding a simple condition to your select that checks how many hours/days have elapsed since the password was renewed. Use a timespan to validate the elapsed time, like this:
var persons = from p in contex.Persons
select new Person
{
Name = p.Name,
HasRenewedPassword = (DateTime.Now - p.LastRenewedPassword).TotalDays > 1;
}
精彩评论