如何仅比较 EF 中 DateTime 中的日期组件? [英] How to compare only date components from DateTime in EF?

查看:39
本文介绍了如何仅比较 EF 中 DateTime 中的日期组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个日期值,一个已经存储在数据库中,另一个由用户使用 DatePicker 选择.用例是从数据库中搜索特定日期.

I am having two date values, one already stored in the database and the other selected by the user using DatePicker. The use case is to search for a particular date from the database.

之前在数据库中输入的值始终具有 12:00:00 的时间分量,而从选择器输入的日期具有不同的时间分量.

The value previously entered in the database always has time component of 12:00:00, where as the date entered from picker has different time component.

我只对日期组件感兴趣,想忽略时间组件.

I am interested in only the date components and would like to ignore the time component.

在 C# 中有哪些方法可以进行这种比较?

What are the ways to do this comparison in C#?

另外,如何在 LINQ 中执行此操作?

Also, how to do this in LINQ?

更新:在 LINQ to Entities 上,以下工作正常.

UPDATE: On LINQ to Entities, the following works fine.

e => DateTime.Compare(e.FirstDate.Value, SecondDate) >= 0

推荐答案

注意: 在撰写此答案时,EF 关系尚不清楚(在此之后被编辑到问题中书面).如需使用 EF 的正确方法,请查看 Mandeeps 答案.

NOTE: at the time of writing this answer, the EF-relation was unclear (that was edited into the question after this was written). For correct approach with EF, check Mandeeps answer.

您可以使用 DateTime.Date 属性来执行仅日期比较.

You can use the DateTime.Date property to perform a date-only comparison.

DateTime a = GetFirstDate();
DateTime b = GetSecondDate();

if (a.Date.Equals(b.Date))
{
    // the dates are equal
}

这篇关于如何仅比较 EF 中 DateTime 中的日期组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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