使用Linq查询仅将日期与DateTime字段进行比较 [英] Use Linq query to compare date only with DateTime field

查看:1721
本文介绍了使用Linq查询仅将日期与DateTime字段进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只需要在一个包含 datetime 字段的Linq查询中比较日期。但是,下面的语法会导致以下错误消息:



LINQ to Entities不支持指定的类型成员'Date'。只有初始化器,实体成员和实体导航属性才被支持。



有谁知道如何从 datetime 字段?

  var duplicate = from _ in _db.AgentProductTraining 
其中a.CourseCode == course.CourseCode&&
a.DateTaken.Date == course.DateTaken.Date&&&
a.SymNumber == symNumber
select a;


解决方案

可能看起来有点迂回,但可以使用SqlFunctions类' DateDiff 这样做的方法。只需传递这两个值,并使用Day来查找它们之间的差异(如果它们在同一天应该为0)。



像以下:$ /

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
SqlFunctions.DateDiff(DAY,a.DateTaken,course.DateTaken)== 0&&&
a.SymNumber == symNumber
select a;


I need to compare just the date only in a Linq query that involves a datetime field. However, the syntax below results in the following error message

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

Does anyone know how to extract just the date out of a datetime field?

var duplicate = from a in _db.AgentProductTraining
                where a.CourseCode == course.CourseCode &&
                a.DateTaken.Date == course.DateTaken.Date &&
                a.SymNumber == symNumber
                select a;

解决方案

It might seem a little roundabout, but you can use the SqlFunctions class' DateDiff method for doing this. Just pass in both values and use "Day" for finding the difference between them in days (which should be 0 if they are on the same day).

Like the following:

from a in _db.AgentProductTraining
                where a.CourseCode == course.CourseCode &&
                SqlFunctions.DateDiff("DAY", a.DateTaken, course.DateTaken) == 0 &&
                a.SymNumber == symNumber
                select a;

这篇关于使用Linq查询仅将日期与DateTime字段进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆