How to compare only date components from DateTime in EF?

后端 未结 14 968
野性不改
野性不改 2020-11-27 17:06

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

相关标签:
14条回答
  • 2020-11-27 17:21

    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();
    
    0 讨论(0)
  • 2020-11-27 17:22

    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

    0 讨论(0)
  • 2020-11-27 17:22

    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;
    
    0 讨论(0)
  • 2020-11-27 17:25

    If you use the Date property for DB Entities you will get exception:

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

    You can use something like this:

      DateTime date = DateTime.Now.Date;
    
      var result = from client in context.clients
                   where client.BirthDate >= date
                         && client.BirthDate < date.AddDays(1)
                   select client;
    
    0 讨论(0)
  • 2020-11-27 17:30

    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.


    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
    }
    
    0 讨论(0)
  • 2020-11-27 17:32

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

    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.

    0 讨论(0)
提交回复
热议问题