1

我试图从数据库中取回三列,DecalExpireDate、DecalExpireMonth 和 DecalExpireYear。基本上,我正在尝试检查它是否有之前的到期日期,如果有,我需要获取最新的到期日期,因为它可能有多个之前的到期日期。

var previousExpirationDate = (from d in db.CT_Decals
      where d.TankID == decal.TankID
      && d.DecalStatus == "Approved"
      && d.DecalExpireDate == ((from dn in db.CT_Decals
                               where dn.TankID == decal.TankID
                               && dn.DecalStatus == "Approved"
                               select dn.DecalExpireDate).Max())
      select new 
      {
        d.DecalExpireDate,
        d.DecalExpireMonth,
        d.DecalExpireYear

      }); 

此查询不起作用,任何人都可以看到问题吗?我正在按 TankID 进行搜索,状态 = 已批准,然后我尝试使用最大过期日期。

4

3 回答 3

1

这个怎么样

 var result = db.CT_Decals.Where(o => o.TankId ==  decal.TankId && o.DecalStatus == "Approved")
                  .OrderByDescending(o => o.DecalExpireDate)
                  .Select(o => new { o.DecalExpireDate,
                                     o.DecalExireMonth,
                                     o.DecalExireYear }).First()

或者

var result = (from d in db.CT_Decals
                      where d.TankID == 1 && d.Status == "Approved"
                      orderby d.ExpireDate descending
                      select new { d.DecalExpireDate, 
                                   d.DecalExpireMonth, 
                                   d.ExpireDate }).First();
于 2012-07-06T18:24:05.197 回答
0

无法Sql在您需要的范围内将 max 函数转换为问题,因此您可以像这样尝试

 var previousExpirationDate = (from d in db.CT_Decals
  where d.TankID == decal.TankID
  && d.DecalStatus == "Approved"
  && d.DecalExpireDate == ((from dn in db.CT_Decals
                           where dn.TankID == decal.TankID
                           && dn.DecalStatus == "Approved"
                           order by dn.DecalExpireDate
                           select dn.DecalExpireDate).First())
  select new 
  {
    d.DecalExpireDate,
    d.DecalExpireMonth,
    d.DecalExpireYear

  }); 
于 2012-07-06T18:27:33.423 回答
0

尽管Max可能是您的示例中的问题,但最好找到一种正确使用它的方法,因为它比排序更快。怎么样:

编辑:这个答案只返回 DecalExpireDate

var previousExpirationDate = (from d in db.CT_Decals
      where d.TankID == decal.TankID
      && d.DecalStatus == "Approved"
      select new 
      {
        d.DecalExpireDate,
        d.DecalExpireMonth,
        d.DecalExpireYear
      }).Max(d => d.DecalExpireDate); 

对于这个版本,您必须测试是否值得额外调用数据库以避免排序:

var latestDate = (from d in db.CT_Decals
      where d.TankID == decal.TankID
      && d.DecalStatus == "Approved"
      select d.DecalExpireDate).Max();

var previousExpirationDate = (from d in db.CT_Decals
      where d.TankID == decal.TankID
      && d.DecalStatus == "Approved"
      && d.DecalExpireDate == latestDate
      select new 
      {
        d.DecalExpireDate,
        d.DecalExpireMonth,
        d.DecalExpireYear
      }).First();
于 2012-07-06T19:41:56.707 回答