简体   繁体   中英

How to get a short DateTime from SQL Server database and compare with DateTime.Now using Linq c#

My table has a column dates of date datatype in a shortDate format '2018/2/12'.

Now I wish to retrieve the date using a Linq query in C#.

This is the query I run on SQL Server, and it returns some rows:

select * 
from tbl_Attendance 
where Dates = '2018/2/12'

But if I try running these queries it either returns null or "Method cannot be translated into a store expression" error.

Only the following query returned the right ID but incorrect Date.

var q = (from a in context.tbl_Attendance
         where a.ID.Value.CompareTo(Iden) < 0 && a.Dates.Value.CompareTo(DateTime.Now) < 0
         select a).FirstOrDefault();

and:

var q = (from a in context.tbl_Attendance
         where a.Dates == DateTime.Now
         select a).FirstOrDefault();

and:

var q = (from a in context.tbl_Attendance
         where a.Dates.Value.ToShortDateString() == DateTime.Now.ToShortDateString()                                               
         select a).FirstOrDefault();

Lastly I have also tried:

attendance = context.tbl_Attendance.Where(d => d.ID == row.xID && d.Dates == DateTime.Now).FirstOrDefault();
  1. If you want to compare a date with another date, you don't have to use DateTime.Now because it also compares the time part. Use DateTime.Today instead.

  2. The error

Method cannot be translated into a store expression

comes up because DateTime.Now.ToShortDateString() or CompareTo() can't be translated into a SQL query.

My suggestion: Declare a variable first, assign the value to it and query your database in a second step.

Code:

DateTime myDate = DateTime.Today; // or DateTime.Parse("2018/2/12")
var result = (from a in context.tbl_Attendance
         where a.Dates == myDate 
         select a).FirstOrDefault();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM