实体框架 6.1.3:运行几天后出现 InvalidOperationException

Grz*_*cki 6 .net c# entity-framework windows-services

我有一个奇怪的问题。我有一个 Windows 服务。服务在 100 多台计算机上运行正常。但是在几天(甚至一个月)后,在其中的一些情况下,它开始抛出如下异常:

System.InvalidOperationException:无法将“Y”上的“X”属性设置为“System.String”值。您必须将此属性设置为“System.Int32”类型的非空值。

在 System.Data.Entity.Core.Common.Internal.Materialization.Shaper.ErrorHandlingValueReader`1.GetValue(DbDataReader reader, Int32 ordinal)

在 System.Data.Entity.Core.Common.Internal.Materialization.Shaper.GetPropertyValueWithErrorHandling[TProperty] (Int32 ordinal, String propertyName, String typeName)



System.Data.Entity.Core.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly[TEntity](Func`2constructEntityDelegate, EntityKey entityKey, EntitySet entitySet)中的 lambda_method(Closure , Shaper )



System.Data.Entity.Core.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper)中的 lambda_method(Closure , Shaper )

中 System.Data.Entity.Core.Common.Internal.Materialization.Shaper`1。 SimpleEnumerator.MoveNext()

在 System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 源)

在 System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 源)

数据库结构中的代码没有任何修改。在几个地方抛出异常。其他应用程序(不是 Windows 服务)使用相同的数据库正常运行。由于我可以检查某些查询运行正常,因此只有少数查询会引发此异常。类型多种多样。有时它不能从字符串转换为 int32,有时(在其他查询中)它不能从 int32 转换为字符串。

要解决此问题,我们必须重新启动 Windows 服务。

我的记忆没有任何问题(我的第一个嫌疑人)。服务使用大约 100-150MB 的内存。

环境:Framework 4.0、EF 6.1.3、64位、SQL Server 2012 Express。

Bar*_*r J 0

似乎需要在这里做很多日志记录工作。我建议,首先,调试案例并在代码抛出异常的每个位置写入日志。

作为预防措施,请尝试尽可能检查对象中的属性是否可转换 - 使用int.TryParse

if(int.TryParse(X, out intVar) 
{
}
else
{
   //failed to convert  
}
Run Code Online (Sandbox Code Playgroud)

还可以使用 try catch 并发出带有确切堆栈跟踪的日志错误,这对于字符串异常来说是更好的选择,因为您无法对字符串属性进行 try 解析。

这里没有简单的方法,你必须一点一点地挖掘它。