LINQ - 从字符串类型的日期获取年份

LINQ - To Get Year from Date which is of Type String

我有这个 LINQ 查询:

  hdms = from t in db.HOLIDAY
         join t1 in db.EMPLOYEE on t.UPDATED_BY equals t1.EMP_CODE                               
         where
             t.HOLIDAY_NAME == searchtext &&                                   
             t.DOH.Value.Year == 2016
         orderby
             t.DOH
         select new HOLIDAYDETAILS
         {
             HOLIDAY_NAME = t.HOLIDAY_NAME,
             DOH = t.DOH,
             EMP_NAME = t1.EMP_NAME                                   
         };

执行此操作时,出现以下错误:

'string' does not contain a definition for 'Value' and no extension method 'Value' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)

t.DOH.Value.Year = 2016 中的 Value 下出现错误。

这里t.DOH的类型是string,值是2016-04-14

我也试过这个:

       hdms = from t in db.HOLIDAY                           
                       where                               
                           DateTime.ParseExact(t.DOH, "yyyy-MM-dd", CultureInfo.InvariantCulture).Year == DateTime.Now.Year
                       orderby
                           t.DOH
                       select new HOLIDAYDETAILS
                       {                               
                           DOH = t.DOH                               
                       };

现在出现这个错误:

LINQ to Entities does not recognize the method 'System.DateTime ParseExact(System.String, System.String, System.IFormatProvider)' method, and this method cannot be translated into a store expression.

在 LINQ 中还有其他方法可以将字符串转换为日期类型吗?

您可以从以下字符串中解析 DateTime:

DateTime.ParseExact(t.DOH, "yyyy-MM-dd", CultureInfo.InvariantCulture)

然后您可以使用 [DateTimeVariable].Year

获取年份值

由于 DOH 是字符串类型,您可以使用 StartsWith 来检查字符串是否以 2016 开头。

where
  t.HOLIDAY_NAME == searchtext &&                                   
  t.DOH.StartsWith("2016")

更好的选择是将 DOH 的数据类型更改为 DateTime/DatetTime?,以便在处理日期和时间值时获得更好的支持。然后您可以保留您的查询。