簡體   English   中英

如何使用 linq 將日期時間 sql 轉換為 c#?

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

下面是我的 sql 代碼: SELECT * FROM test.operator_error_transaction WHERE operator_token = 12345 && transaction_date_time BETWEEN '2019-05-22';

我在下面嘗試了我的 c# 代碼,但在比較日期時間時遇到了一些錯誤:

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

您應該使用 DateTime 類型進行轉換。

 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.ToDateTime("2019-05-22")

我建議:

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

這避免了與文化和日期格式相關的任何問題。 並且它獲取交易發生在 2019 年 5 月 22 日某人的所有數據(無論時間部分)並且具有良好的性能特征

sql 日期格式為 YYYY-MM-DD,c# 日期格式為 DD-MM-YYYY。

請更改任一日期格式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM