简体   繁体   中英

How may I convert the datetime sql to c# by using linq?

Below is my sql code: SELECT * FROM test.operator_error_transaction WHERE operator_token = 12345 && transaction_date_time BETWEEN '2019-05-22';

I have tried my c# code below and got some error in comparing the datetime:

var id = (from firstn in _context.OperatorErrorTransaction
                  where firstn.OperatorToken == "12345"
                  where firstn.TransactionDateTime >= '2019-05-22'
                  select firstn).ToList();
        return Ok(id);

You should use DateTime type for conversion.

 var mydate = Convert.ToDateTime("2019-05-22");
 var id = (from firstn in _context.OperatorErrorTransaction
                  where firstn.OperatorToken == "12345"
                  where firstn.TransactionDateTime >= mydate 
                  select firstn).ToList();
        return Ok(id);

Convert your string to datetime. This will work.

Convert.ToDateTime("2019-05-22")

I'd suggest:

var startInclusive= new DateTime(2019,5,22); // if you really must, use `DateTime.TryParseExact` here
var endExclusive = startInclusive.AddDays(1);

var id = (from firstn in _context.OperatorErrorTransaction
            where firstn.OperatorToken == "12345"
                  && firstn.TransactionDateTime >= startInclusive
                  && firstn.TransactionDateTime < endExclusive
            select firstn).ToList();
return Ok(id);

This avoids any issues relating to culture and date formats. And it gets all data where the transaction occurred someone on 22 May 2019 (whatever the time component) and has good performance characteristics .

sql date format is YYYY-MM-DD and c# date format is DD-MM-YYYY.

Please change either of the date formats.

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