Select()内部的布尔值

时间:2011-10-10 14:40:28

标签: c# .net linq entity-framework linq-to-entities

我有一个填充了人员信息的人员表。我想得到一个表内人员列表,检查他们是否在过去24小时内更新了他们的密码,然后返回一个人名和一个布尔属性,无论他们是否更新了密码。

这是我的人员表:

人员表:

varchar(30) Name,
DateTime LastRenewedPassword.

代码:

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?
                      }
    }
}

所以我的问题是,如果有人更新了密码,我该如何选择新的{...}返回?

所有帮助都是适当的! 我打开其他任何解决此问题的建议。

6 个答案:

答案 0 :(得分:8)

听起来像你想要的东西:

// 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
                  };
}

(通过评估DateTime.Now 一次并在客户端,可能更容易调试随时发生的事情 - 例如,您可以记录该查询参数。)

请注意,由于您只进行了投影,因此可以稍微简化一下代码:

var persons = context.Persons.Select(p => new Person {
                  Name = p.Name,
                  HasRenewedPassword = p.LastRenewedPassword > renewalCutoff
              });

答案 1 :(得分:7)

好吧,我正在猜测之类的东西:

var cutoff = DateTime.Now.AddDays(-1);
...
 select new Person
  {
      Name = p.Name,
      HasRenewedPassword = p.PasswordChanged >= cutoff
  }

答案 2 :(得分:2)

尝试

select new Person
{
         Name = p.Name,
         HasRenewedPassword = (DateTime.Now - p.LastRenewedPassword).TotalHours <= 24
}

答案 3 :(得分:0)

您可以使用TimeSpan:

HasRenewedPassword = (DateTime.Now - p.LastRenewedPassword).TotalHours <= 24

答案 4 :(得分:0)

var renewalTime = DateTime.Now.Substract(new TimeSpan(24,0,0));

// insert in the select code
HasRenewedPassword = p.LastRenewedPassword > renewalTime

答案 5 :(得分:0)

您可以通过向select添加一个简单条件来设置此值,该条件用于检查自密码更新以来经过的小时数/天数。使用时间跨度来验证已用时间,如下所示:

var persons = from p in contex.Persons 
              select new Person 
              { 
                  Name = p.Name, 
                  HasRenewedPassword = (DateTime.Now - p.LastRenewedPassword).TotalDays > 1;
              }