【问题标题】:casting to datetime data to month and year in C#在 C# 中将日期时间数据转换为月份和年份
【发布时间】:2014-03-25 17:43:56
【问题描述】:

我在下面有 linq 到实体查询,但我希望 where 子句在它之后使用示例 T-SQL 代码中的逻辑。

var myList = from p in ctx.myTable
               where !ctx.Report.Any(m =>  m.ReportDate == DateTime.Today && m.ReportDate ==  DateTime.Today)
               select p;

我怎样才能像下面的 T-SQL 那样在 where 子句中比较月份和年份?

WHERE month(R.ReportDate) = month(GETDATE()) AND YEAR(R.ReportDate) = YEAR(GETDATE()))

【问题讨论】:

    标签: c# tsql c#-4.0 datetime


    【解决方案1】:

    在 LINQ to Entities 中处理日期有点棘手。 我不确定您是否可以在 SQL 中生成 MONTH()YEAR()。但是您绝对可以使用正确的my 作为日期部分来生成DATEPART 调用。

    使用SqlFunctions.DatePart Method (String, String) 来做到这一点:

    var todayMonth = DateTime.Today.Month;
    var todayYear = DateTime.Today.Year;
    
    var myList = from p in ctx.myTable
                 where !ctx.Report.Any(m => SqlFunctions.DatePart("m", m.ReportDate) == todayMonth && SqlFunctions.DatePart("y", m.ReportDate) ==  todayYear)
                 select p;
    

    应该生成

    WHERE DATEPART(m, R.ReportDate) = 2 AND DATEPART(y, R.ReportDate) = 2014)
    

    如果你真的想要GETDATE() 部分,你可以使用以下:

    var myList = from p in ctx.myTable
                 where !ctx.Report.Any(m => SqlFunctions.DatePart("m", m.ReportDate) == SqlFunctions.DatePart("m", SqlFunctions.GetDate()) && SqlFunctions.DatePart("y", m.ReportDate) ==  SqlFunctions.DatePart("y", SqlFunctions.GetDate()))
                 select p;
    

    更新

    我刚刚找到该页面:CLR Method to Canonical Function Mapping 其中指出,DateTime.MonthDateTime.Year 属性被转换为 MONTHYEAR 方法,所以以下应该可以正常工作:

    var myList = from p in ctx.myTable
                 where !ctx.Report.Any(m => m.ReportDate.Month == SqlFunctions.GetDate().Month && m.ReportDate.Year ==  SqlFunctions.GetDate().Year)
                 select p;
    

    【讨论】:

      【解决方案2】:

      DateTime 对象具有 MonthYear 属性。你可以利用它。

      DateTime dateTime = new DateTime();
                  if (dateTime.Month > DateTime.Today.Month) { 
                  // Do something
                  }
      
                  if (dateTime.Year> DateTime.Today.Year)
                  {
                      // Do something
                  }
      

      【讨论】:

        【解决方案3】:

        由于 DateTime 包含年份和月份,请尝试以下操作。

        where !ctx.Report.Any(m =>  m.ReportDate.Month == DateTime.Today.Month &&                              m.ReportDate.Year ==  DateTime.Today.Year)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-12-24
          • 1970-01-01
          • 1970-01-01
          • 2021-09-26
          • 2021-07-04
          • 2021-12-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多