Programming

EF에서 DateTime의 날짜 구성 요소 만 비교하는 방법은 무엇입니까?

procodes 2020. 7. 22. 22:20
반응형

EF에서 DateTime의 날짜 구성 요소 만 비교하는 방법은 무엇입니까?


두 개의 날짜 값이 있습니다. 하나는 이미 데이터베이스에 저장되어 있고 다른 하나는 DatePicker를 사용하여 사용자가 선택했습니다. 유스 케이스는 데이터베이스에서 특정 날짜를 검색하는 것입니다.

데이터베이스에 이전에 입력 한 값의 시간 구성 요소는 항상 12:00:00입니다. 여기서 picker에서 입력 한 날짜는 다른 시간 구성 요소입니다.

날짜 구성 요소에만 관심이 있고 시간 구성 요소를 무시하고 싶습니다.

C #에서이 비교를 수행하는 방법은 무엇입니까?

또한 LINQ 에서이 작업을 수행하는 방법은 무엇입니까?

업데이트 : LINQ to Entities에서 다음이 정상적으로 작동합니다.

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

참고 : 이 답변을 작성할 당시 EF 관계는 불분명했습니다 (이 내용은 작성된 후 질문으로 편집되었습니다). EF에 대한 올바른 접근 방법은 Mandeeps answer를 확인하십시오 .


DateTime.Date속성을 사용하여 날짜 만 비교할 수 있습니다.

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

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

EntityFunctions시간 부분을 다듬기 위해 클래스 사용하십시오 .

using System.Data.Objects;    

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

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

최신 정보

EF 6.0 이상 EntityFunctions 현재로 대체 DbFunctions .


나는 이것이 당신을 도울 수 있다고 생각합니다.

EF 데이터로 채워진 리포지토리의 날짜를 비교해야하므로 확장 프로그램을 만들었으므로 LinqToEntities 번역으로 구현되지 않았으므로 날짜는 옵션이 아닙니다.

코드는 다음과 같습니다.

        /// <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);
    }

그런 식으로 사용할 수 있습니다.

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

DateDB 엔터티에 속성을 사용하면 예외가 발생합니다.

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

다음과 같은 것을 사용할 수 있습니다.

  DateTime date = DateTime.Now.Date;

  var result = from client in context.clients
               where client.BirthDate >= date
                     && client.BirthDate < date.AddDays(1)
               select client;

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.


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

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


You can also use this:

DbFunctions.DiffDays(date1, date2) == 0


you can use DbFunctions.TruncateTime() method for this.

e => DbFunctions.TruncateTime(e.FirstDate.Value) == DbFunctions.TruncateTime(SecondDate);

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

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

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

This is how I do this.

DateTime date_time_to_compare = DateTime.Now;
//Compare only date parts
context.YourObject.FirstOrDefault(r =>
                EntityFunctions.TruncateTime(r.date) == EntityFunctions.TruncateTime(date_to_compare));

//Note for Linq Users/Coders

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.


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;

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

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


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

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();

참고URL : https://stackoverflow.com/questions/1478215/how-to-compare-only-date-components-from-datetime-in-ef

반응형