如何在LINQ中使用Date函数实体?

gog*_*gog 5 c# linq linq-to-entities entity-framework

我的方法应该返回一个用户注释列表,所以我这样做:

  var saturday = DayOfWeek.Saturday;
  var query = from note in userNotes
  where note.NoteDate > lastMonth && note.NoteDate.DayOfWeek != saturday
        select note;
Run Code Online (Sandbox Code Playgroud)

但我得到这个错误:

LINQ to Entities不支持指定的类型成员"Date".仅初始化程序,实体成员和实体导航属性.

有关如何使用linq比较星期几的任何想法?

Mar*_*zek 16

使用SqlFunctions.DatePart静态方法.它将转换为DATEPARTTSQL函数调用.

var saturday = (int)DayOfWeek.Saturday;
var query = from note in userNotes
            where note.NoteDate > lastMonth && SqlFunctions.DatePart("dw", note.NoteDate) != saturday
            select note;
Run Code Online (Sandbox Code Playgroud)

  • 对于 EF,您需要 `EntityFunctions`。 (2认同)
  • 一点警告,"DatePart"的结果依赖于SQL Server中的"第一个工作日设置",另一种方法是:http://c-sharp-snippets.blogspot.de/2011/12/getting-dayofweek -in-LINQ到entities.html (2认同)