伙计们,我在 Entity Framework 和 DateTime 方面遇到了一个大问题。问题在这里:
首先是实体:
当用户提交表单时,系统会根据用户输入的参数为条件查询创建这些值。示例:
var query = from user in UserTable
select user;
if(Request.Form["Category"])
{
query = query.where(add=>add.Category == Request.Form["Category"])
}
//and here the between
if(Request.Form["start_date"] && Request.Form["end_date"])
{
query = query.where(add=>add.Date < Request.Form["start_date"] && add.Date > Request.Form["end_date"] )//equivalent to between
}
until...
return query.ToList();
很好,但问题仍然存在,当用户想要按日期搜索时,将请求表单转换为日期时间时,格式与接收到的输入不同:
User'input
2003-12-02
Convert.ToDateTime
result : 02/11/2003(not iqual to the user input)
所以,这不是巧合(好吧,这就是我的客人,因为我读到那个实体自己解决了这个问题)。而且我不能将日期属性设置为字符串,因为我不能在字符串之间使用。
这里的模型简化了:
public string Category {get;set;}
public DateTime Date{get;set;}
但这还不是全部
第 2 部分
我尝试以 02/11/2003
格式进行查询,以查看查询是否有效并且是否正确执行,但是当我尝试使用 2003-12-02
时,这是结果
02/12/2003 format
16330 rows
2003-12-02 format
136 rows
请注意,它们相同但返回不同的结果。此外,当我检查结果时,我注意到以 02/12/2003 格式查询时
结果包括更小或更早的日期:
例子:
Select date FROM Table WHERE date BETWEEN 02/12/2003 AND 03/12/2003
results include: 05/12/2003,30/12/2003
为什么这两个查询之间存在如此显着的差异?
最佳答案
这与您的数据库文化有关。您可以通过执行以下命令来检查您当前的文化:
SELECT @@language
要查看您的文化的日期格式,请执行:
EXEC sp_helplanguage
基于此,您可以在 C# 中使用您的特定文化 Convert.ToDateTime()
,如下所示:
更新的答案
DateTime startDate = DateTime.MinValue;
DateTime endDate = DateTime.MaxValue;
// Set this to your culture if it's not en-US
DateTimeFormatInfo usDtfi = new CultureInfo("en-US", false).DateTimeFormat;
try { startDate = Convert.ToDateTime(Request.Form["start_date"], usDtfi); }
catch {}
try { endDate = Convert.ToDateTime(Request.Form["end_date"], usDtfi); }
catch {}
if (startDate != DateTime.MinValue && endDate != DateTime.MaxValue)
{
query = query.where(add=>add.Date <= endDate && add.Date >= startDate ) //equivalent to between
}
请注意,您的日期倒退了。您有 < startDate 和 > endDate。这与 BETWEEN
相反。 (除非您认为 startDate 是两个日期中较大的一个,而我不是。)
关于c# - Entity Framework 中的 DateTime && sql 格式的 DateTime 返回不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16196650/