在 LINQ to Entities 中处理日期有点棘手。 我不确定您是否可以在 SQL 中生成 MONTH() 或 YEAR()。但是您绝对可以使用正确的m 或y 作为日期部分来生成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.Month 和 DateTime.Year 属性被转换为 MONTH 和 YEAR 方法,所以以下应该可以正常工作:
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;