Select()内部的布尔值

Eri*_*son 7 .net c# linq linq-to-entities entity-framework

我有一个填充了人员信息的人员表.我想获得的表内personer的列表,并检查他们是否在过去24小时内重新thier密码,然后返回一个人的名字和一个布尔属性是否已经更新了密码或者没有.

这是我的Person表:

人员表:

varchar(30) Name,
DateTime LastRenewedPassword.
Run Code Online (Sandbox Code Playgroud)

码:

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?
                      }
    }
}
Run Code Online (Sandbox Code Playgroud)

所以我的问题是,如果有人更新密码,我可以在选择新的{...}返回内部吗?

所有的帮助都很有用!我打开任何其他建议来解决这个问题.

Jon*_*eet 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
                  };
}
Run Code Online (Sandbox Code Playgroud)

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

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

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


Mar*_*ell 7

好吧,我是这样的:

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