C# LINQ ToList()方法引发FormatException:字符串未被识别为有效的日期时间
异常的堆栈跟踪是:C# LINQ ToList()方法引发FormatException:字符串未被识别为有效的日期时间,c#,linq,datetime,formatexception,C#,Linq,Datetime,Formatexception,异常的堆栈跟踪是: System.FormatException: String was not recognized as a valid DateTime. at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles) at lambda_method(Closure , **MyType** ) at System.Linq.Enumerable.WhereListIter
System.FormatException: String was not recognized as a valid DateTime.
at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi,
DateTimeStyles styles)
at lambda_method(Closure , **MyType** )
at System.Linq.Enumerable.WhereListIterator`1.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
MyType映射到DB中的一个表,该表的列类型为date
现在,在我的代码中,我有以下方法:
private static List<T> MyMethod<T>(IEnumerable<T> results)
{
if (results == null)
{
return null;
}
var filteredResults = results.AsQueryable();
return filteredResults.ToList();
}
私有静态列表MyMethod(IEnumerable结果)
{
如果(结果==null)
{
返回null;
}
var filteredResults=results.AsQueryable();
返回filteredResults.ToList();
}
第行出现异常:return filteredResults.ToList()
保存在DB中的格式为:2016-12-14
(YYYY-MM-DD)。
我了解(通过阅读有关此问题的其他线程)此问题可能与服务器的区域性或时间/日期设置有关。然而,我还没有成功地重现这个异常。您对如何重现或防止此问题有何建议?在这些情况下,有时可以在您的类型中添加额外的字符串属性以避免数据绑定问题。然后可以将数据库值写入该字符串字段,然后以受控方式将其转换为另一个字段中的DateTime
public class PocoObject
{
public string DateString { get; set; }
public DateTime Date
{
get
{
DateTime date;
return DateTime.TryParseExact(DateString,
"yyyy-MM-dd",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out date)
? date : DateTime.MinValue;
}
}
}
如果您没有显示您在哪里创建
结果
,我们将无法帮助修复它。异常在ToList
处引发,因为这是执行查询的地方。为什么不将datetimes存储为数据库中的datetime?结果包含来自DB的项,而无需任何操作。为什么我是否将datetimes保存为datetime而不是date很重要?在Debug(在C#代码中)中,我可以看到实体包含有效的datetime属性。你认为这就是问题的原因吗?嗯,一定是某个地方的代码使用了DateTime.Parse
或System.Convert.ToDateTime
。这意味着您有一个字符串,需要将其解析为DateTime。这就提出了一个问题,为什么它不是数据库中的datetime
,或者-如果它存储为datetime-为什么在再次将其解析为datetime
之前将其转换为字符串。我想我没有使用datetime.parse或System.convert.ToDateTime的代码。为什么异常发生在LINQ.TOLIST()上,而不是parse或convert.ToDateTime行(如果我确实有这些行的话)?作为结果传递的LINQ表达式只有在您枚举它时才会计算,在您调用TOLIST()
时才会计算。stacktrace显示,results
在Where
子句中的某处使用Parse
。