【发布时间】:2015-04-04 16:14:43
【问题描述】:
我在比较 linq 中的两个日期范围时遇到问题。我的视图抛出异常
没有为类型定义二元运算符 Equal “System.DateTime”和“System.Object”。请问我该如何解决这个问题? 任何帮助将不胜感激。
public ViewResult List(SearchTerms search, int page = 1)
{
(from posts in repository.JobPosts
orderby posts.PostDate descending
select new
{
Id = posts.Id,
......
})
.Where(x => ((search.PostedDateFrom.CompareTo(DbFunctions.TruncateTime(DateTime.Now.Date)) != 0
|| (search.PostedDateTo.CompareTo(DbFunctions.TruncateTime(DateTime.Now.Date)) != 0)) ?
x.PostDate >= search.PostedDateTo && x.PostDate <= search.PostedDateTo : x.PostDate !=null)
)).....
}
我的搜索词模型。
public class SearchTerms
{
public string searchText { get; set; }
public string JobFunction { get; set; }
public string JobIndustry { get; set; }
public string jobType { get; set; }
public string JobLevel { get; set; }
public DateTime PostedDateFrom { get; set; }
public DateTime PostedDateTo { get; set; }
public decimal MinSalary { get; set; }
public string JobRegion { get; set; }
}
任何帮助将不胜感激。
更新
下面是我的 JobPost 模型。
public class JobPost
{
public long Id { get; set; }
public string Post { get; set; }
public DateTime PostDate { get; set; }
public long UserId { get; set; }
public string Region { get; set; }
public string JobType { get; set; }
public string PostTitle { get; set; }
public string Industry { get; set; }
public string JobFunction { get; set; }
public string JobLevel { get; set; }
public decimal Salary { get; set; }
public int Experience { get; set; }
public DateTime JobExpiryDate { get; set; }
public bool Active { get; set; }
}
【问题讨论】:
-
你确定你的 PostDate 是 DateTime 类型吗?
-
@khlr 它的日期时间。请在上面查看我的更新。
-
你想用
DbFunctions.TruncateTime(DateTime.Now.Date)做什么?DateTime.Now.Date不包含时间,没有可以截断的内容。 -
@NadiaCibrikova,在添加之前,我收到错误“LINQ to Entities 不支持指定的类型成员'日期'。仅初始化程序、实体成员和实体导航属性”。我在网上搜索并被告知比较需要一个可为空的日期时间数据类型。我被告知要添加它以达到我的要求。所以
DbFunctions.TruncateTime只是形式,我的真正价值是DateTime.Now.Date。请问我如何比较两个日期? -
试试 DbFunctions.TruncateTime(DateTime.Now),如果这不起作用,您可以分别比较年、月和日,例如
!(search.PostedDateFrom.Year==DateTime.Now.Year && search.PostedDateFrom.Month==DateTime.Now.Month && search.PostedDateFrom.Day==DateTime.Now.Day)。这有点冗长,但肯定会起作用。