C# 如何仅比较 EF 中 DateTime 中的日期组件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1478215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 17:56:11  来源:igfitidea点击:

How to compare only date components from DateTime in EF?

c#linqentity-frameworklinq-to-entitiesdatetime-comparison

提问by pencilslate

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.

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

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.

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

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

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

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

在 C# 中进行这种比较的方法是什么?

Also, how to do this in LINQ?

另外,如何在 LINQ 中做到这一点?

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

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

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

采纳答案by Fredrik M?rk

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.

注意:在撰写此答案时,EF 关系尚不清楚(在撰写此内容后已编辑到问题中)。对于 EF 的正确方法,请检查Mandeeps 答案



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

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

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

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

回答by Reed Copsey

Just always compare the Dateproperty of DateTime, instead of the full date time.

总是比较DateTime的Date属性,而不是完整的日期时间。

When you make your LINQ query, use date.Date in the query, ie:

当您进行 LINQ 查询时,请在查询中使用 date.Date,即:

var results = from c in collection
              where c.Date == myDateTime.Date
              select c;

回答by Craig Stuntz

To do it in LINQ to Entities, you have to use supported methods:

要在 LINQ to Entities 中执行此操作,您必须使用支持的方法

var year = someDate.Year;
var month = ...
var q = from r in Context.Records
        where Microsoft.VisualBasic.DateAndTime.Year(r.SomeDate) == year 
              && // month and day

Ugly, but it works, and it's done on the DB server.

丑陋,但它有效,而且它是在数据库服务器上完成的。

回答by jrojo

I think this could help you.

我想这可以帮助你。

I made an extension since I have to compare dates in repositories filled with EF data and so .Date was not an option since it is not implemented in LinqToEntities translation.

我做了一个扩展,因为我必须比较充满 EF 数据的存储库中的日期,所以 .Date 不是一个选项,因为它没有在 LinqToEntities 翻译中实现。

Here is the code:

这是代码:

        /// <summary>
    /// Check if two dates are same
    /// </summary>
    /// <typeparam name="TElement">Type</typeparam>
    /// <param name="valueSelector">date field</param>
    /// <param name="value">date compared</param>
    /// <returns>bool</returns>
    public Expression<Func<TElement, bool>> IsSameDate<TElement>(Expression<Func<TElement, DateTime>> valueSelector, DateTime value)
    {
        ParameterExpression p = valueSelector.Parameters.Single();

        var antes = Expression.GreaterThanOrEqual(valueSelector.Body, Expression.Constant(value.Date, typeof(DateTime)));

        var despues = Expression.LessThan(valueSelector.Body, Expression.Constant(value.AddDays(1).Date, typeof(DateTime)));

        Expression body = Expression.And(antes, despues);

        return Expression.Lambda<Func<TElement, bool>>(body, p);
    }

then you can use it in this way.

那么你可以这样使用它。

 var today = DateTime.Now;
 var todayPosts = from t in turnos.Where(IsSameDate<Turno>(t => t.MyDate, today))
                                      select t);

回答by John Kaster

Here's a different way to do it, but it's only useful if SecondDate is a variable you're passing in:

这是一种不同的方法,但仅当 SecondDate 是您传入的变量时才有用:

DateTime startDate = SecondDate.Date;
DateTime endDate = startDate.AddDays(1).AddTicks(-1);
...
e => e.FirstDate.Value >= startDate && e.FirstDate.Value <= endDate

I think that should work

我认为这应该有效

回答by Leo Di Salty

//Note for Linq Users/Coders

//Linq 用户/编码员注意事项

This should give you the exact comparison for checking if a date falls within range when working with input from a user - date picker for example:

这应该为您提供在处理来自用户的输入时检查日期是否在范围内的确切比较 - 例如日期选择器:

((DateTime)ri.RequestX.DateSatisfied).Date >= startdate.Date &&
        ((DateTime)ri.RequestX.DateSatisfied).Date <= enddate.Date

where startdate and enddate are values from a date picker.

其中 startdate 和 enddate 是来自日期选择器的值。

回答by Raskunho

Try this... It works fine to compare Date properties between two DateTimes type:

试试这个……比较两个 DateTimes 类型之间的日期属性很有效:

PS. It is a stopgap solution and a really bad practice, should never be used when you know that the database can bring thousands of records...

附注。这是一个权宜之计,也是一种非常糟糕的做法,当您知道数据库可以带来数千条记录时,永远不要使用它...

query = query.ToList()
             .Where(x => x.FirstDate.Date == SecondDate.Date)
             .AsQueryable();

回答by Nalan Madheswaran

Without time than try like this:

没有时间比这样尝试:

TimeSpan ts = new TimeSpan(23, 59, 59);
toDate = toDate.Add(ts);
List<AuditLog> resultLogs = 
    _dbContext.AuditLogs
    .Where(al => al.Log_Date >= fromDate && al.Log_Date <= toDate)
    .ToList();
return resultLogs;

回答by Mandeep Janjua

Use the class EntityFunctionsfor trimming the time portion.

使用该类EntityFunctions来修剪时间部分。

using System.Data.Objects;    

var bla = (from log in context.Contacts
           where EntityFunctions.TruncateTime(log.ModifiedDate) ==  EntityFunctions.TruncateTime(today.Date)
           select log).FirstOrDefault();

Source: http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/84d4e18b-7545-419b-9826-53ff1a0e2a62/

来源:http: //social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/84d4e18b-7545-419b-9826-53ff1a0e2a62/

UPDATE

更新

As of EF 6.0 and later EntityFunctions is replaced by DbFunctions.

由于EF 6.0及更高版本EntityFunctions的被替换DbFunctions

回答by majid

You can user below link to compare 2 dates without time :

您可以使用以下链接来比较 2 个没有时间的日期:

private bool DateGreaterOrEqual(DateTime dt1, DateTime dt2)
        {
            return DateTime.Compare(dt1.Date, dt2.Date) >= 0;
        }

private bool DateLessOrEqual(DateTime dt1, DateTime dt2)
        {
            return DateTime.Compare(dt1.Date, dt2.Date) <= 0;
        }

the Compare function return 3 different values: -1 0 1 which means dt1>dt2, dt1=dt2, dt1

比较函数返回 3 个不同的值:-1 0 1 表示 dt1>dt2, dt1=dt2, dt1