简体   繁体   English

LINQ 查询比较 DateTime 列与 DateTime 字符串列

[英]LINQ query compare DateTime column to DateTime string column

I have a table with 3 columns like below:我有一个包含 3 列的表格,如下所示:

DeliveryDate(string) | 2020-06-16
DeliveryTime(string) | 20:00:00
EstimateDeliveryDateTime(DateTime) | 2020-06-15 20:00:00.232

I wrote below condition in LINQ, expect it convert to sql by ef core, but failed.我在 LINQ 中写了以下条件,期望它通过 ef 核心转换为 sql,但失败了。 EstimateDeliveryDateTime > Convert.ToDateTime(DeliveryDate + DeliveryTime)

I know AsEnumberable().我知道 AsEnumberable()。 But I want this condition to be executed in db, is it doable in LINQ or not?但我希望这个条件在数据库中执行,在 LINQ 中是否可行?

How about using DateTime.ParseExact?使用 DateTime.ParseExact 怎么样?

EstimateDeliveryDateTime > DateTime.ParseExact(DeliveryDate + DeliveryTime, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture")

Hope it will be helpful.希望它会有所帮助。

EstimateDeliveryDateTime > Convert.ToDateTime(DeliveryDate + " " + DeliveryTime) EstimateDeliveryDateTime > Convert.ToDateTime(DeliveryDate + " " + DeliveryTime)

You can write your own method/extention method to convert the string to DateTime according to the string format ie. yyyy-dd-MM hh:mm:ss您可以编写自己的方法/扩展方法来根据字符串格式将字符串转换为 DateTime ie. yyyy-dd-MM hh:mm:ss ie. yyyy-dd-MM hh:mm:ss . ie. yyyy-dd-MM hh:mm:ss
Here is my suggestion:这是我的建议:

Implementation:执行:

private void Example()
{
    string DeliveryDate = "2020-06-16";
    string DeliveryTime = "20:00:00";
    DateTime EstimateDeliveryDateTime = DateTime.Now;

    if (EstimateDeliveryDateTime < DeliveryDate.ToDate(DeliveryTime))
    {
        // do something....
    }
}

Extension Method:扩展方法:

public static DateTime ToDate(this string wanabedate, string wanabetime)
{
    try
    {
        string[] mydate = wanabedate.Split('-').ToArray();
        if (mydate == null || mydate.Length < 3)
        {
            return DateTime.MinValue;
        }

        string[] mytime = wanabetime.Split(':');

        // create date time
        var year = Convert.ToInt32(mydate[0]);
        var day = Convert.ToInt32(mydate[2]);
        var month = Convert.ToInt32(mydate[1]);

        var seconds = Convert.ToInt32(mytime[2]);
        var mins = Convert.ToInt32(mytime[1]);
        var hr = Convert.ToInt32(mytime[0]);

        DateTime result = new DateTime(year, month, day, hr, mins, seconds, 0);

        return result;
    }
    catch (Exception ex)
    {
        return DateTime.MinValue;
    }
}

Finally, I create a sql View convert DeliveryDate + DeliveryTime to one DateTime column.最后,我创建了一个 sql 视图,将 DeliveryDate + DeliveryTime 转换为一个 DateTime 列。 And then use ef core keyless entity to query the View.然后使用 ef core keyless entity 来查询 View。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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