如果日期以字符串格式存储在数据库中,则C#Linq其中2个日期之间的日期

时间:2019-04-02 04:07:10

标签: c# linq

我想在两个日期之间使用c#linq获取数据,但是数据库中存储的日期是字符串格式。

DateTime dFrom = DateTime.ParseExact("01-04-2019", "dd-MM-yyyy", CultureInfo.InvariantCulture);

DateTime dTo = DateTime.ParseExact("02-04-2019", "dd-MM-yyyy", CultureInfo.InvariantCulture);  

 var List = (from Receipt in DB.tbl_PurchaseReceipts 
             where DateTime.ParseExact(Receipt.Date, "dd-MM-yyyy", CultureInfo.InvariantCulture) >= dFrom && DateTime.ParseExact(Receipt.Date, "dd-MM-yyyy", CultureInfo.InvariantCulture) <= dTo
             select Receipt).ToList();

获取错误:

  

Method'System.DateTime ParseExact(System.String,System.String,   System.IFormatProvider)'不支持SQL转换。

1 个答案:

答案 0 :(得分:0)

您应该能够手动解析这些部分并构建一个新的DateTime

var List = (from Receipt in DB.tbl_PurchaseReceipts 
            let rDate = new DateTime(Convert.ToInt32(Receipt.Date.Substring(6,4)),Convert.ToInt32(Receipt.Date.Substring(0,2)),Convert.ToInt32(Receipt.Date.Substring(3,2)))
            where dFrom <= rDate && rDate <= dTo
            select Receipt)
           .ToList();