【问题标题】:FormatException: The string was not recognized as a valid DateTime. There is an unknown word starting at index 0FormatException:该字符串未被识别为有效的 DateTime。有一个从索引 0 开始的未知单词
【发布时间】:2017-06-15 21:31:33
【问题描述】:

我花了 4 天时间尝试让 EF Core 保存记录的日期时间值。 它不断失败并出现以下错误:

FormatException:字符串未被识别为有效的 DateTime。从索引 0 开始有一个未知单词。

我查看了近百篇关于类似无用的帖子。我尝试了多种日期时间格式。下面是 Visual Studio 中最新尝试的链接,其中一些监视设置为相关值。

    var format = "yyyy-MM-dd HH:mm:ss.fff";
    var stringDate = DateTime.Now.ToString(format);
    gl.LastUpdate =DateTime.ParseExact(stringDate,format,CultureInfo.InvariantCulture);
    db.SaveChanges(); //Entity Framework Core

        //model snip
        [Display(Name = "Updated Date")]
        public  DateTime? LastUpdate { get; set; }

我试图查找 EF Core 期望的日期时间格式的文档,但没有成功。

由于此错误,我无法保存我的记录。我认为它必须是相对简单的东西,并希望有人能对此有所了解。

异常详情

Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.FormatException: Failed to convert parameter value from a String to a DateTime. ---> System.FormatException: The string was not recognized as a valid DateTime. There is an unknown word starting at index 0. at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles) at System.Convert.ToDateTime(String value, IFormatProvider provider) at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider) at System.Data.SqlClient.SqlParameter.CoerceValue(Object value, MetaType destinationType, Boolean& coercedToDataFeed, Boolean& typeChanged, Boolean allowStreaming) --- End of inner exception stack trace --- at System.Data.SqlClient.SqlParameter.CoerceValue(Object value, MetaType destinationType, Boolean& coercedToDataFeed, Boolean& typeChanged, Boolean allowStreaming) at System.Data.SqlClient.SqlParameter.GetCoercedValue() at System.Data.SqlClient.SqlParameter.Validate(Int32 index, Boolean isCommandProc) at System.Data.SqlClient.SqlCommand.BuildParamList(TdsParser parser, SqlParameterCollection parameters) at System.Data.SqlClient.SqlCommand.BuildExecuteSql(CommandBehavior behavior, String commandText, SqlParameterCollection parameters, _SqlRPC& rpc) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds) at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior) at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, String executeMethod, IReadOnlyDictionary2 参数值,布尔型 closeConnection) 在 Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection 连接,IReadOnlyDictionary2 parameterValues) at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection) --- End of inner exception stack trace --- at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection) at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(Tuple2 参数) 在 Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](Func2 operation, Func2 verifySucceeded, TState 状态) 在 Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList1 entriesToSave) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess) at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess) at TMain.Models.TmainContext.SaveChanges() in C:\Users\dmcquay\Source\Workspaces\SCM\NET Core\TMainModel\Models\tmainContext.cs:line 123 at TMain.Data.GLConfigurationRepository.SaveChanges() in C:\Users\dmcquay\Source\Workspaces\SCM\NET Core\TMainModel\Data\GLConfigurationRepository.cs:line 40 at GLCoderConfiguration.Controllers.GLConfigController.Save(Int32 id, String userName) in C:\Users\dmcquay\Source\Workspaces\SCM\NET Core\GLCoderConfiguration\Controllers\GLConfigController.cs:line 181 at lambda_method(Closure , Object , Object[] ) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionMethodAsync>d__27.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextActionFilterAsync>d__25.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextResourceFilter>d__22.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResourceExecutedContext context) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeAsync>d__20.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Session.SessionMiddleware.<Invoke>d__9.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at Microsoft.AspNetCore.Session.SessionMiddleware.<Invoke>d__9.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.VisualStudio.Web.BrowserLink.BrowserLinkMiddleware.<ExecuteWithFilter>d__7.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext()

【问题讨论】:

  • 在问题正文中发布您的代码,不要链接到图片或外部代码网站。
  • @dmcquay 将代码粘贴为文本。不是图像。文本。您可以粘贴文本。
  • @dmcquay 点击“编辑”
  • @dmcquay 它就在您的标签下方。
  • EF Core 内部的某个地方。我对 EF Core 比较陌生,但没想到会遇到像将日期时间值保存到数据库这样简单的问题。假设我错过了一些简单的事情。

标签: c# entity-framework-core


【解决方案1】:

更改第二行。您不能在 ToString 方法调用中使用带有 {0: 前缀的格式字符串:

var stringDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

【讨论】:

  • 两种方法都试过了,结果还是一样。
【解决方案2】:

这里的原因是您将 DateTime 值转换为字符串,然后尝试将其解析回 DateTime,并且您为解析指定了一种文化,但没有为格式设置。

所以要么将文化传递给 ToString 方法,要么将其从解析中删除...

不过,只需不在字符串和 DateTime 值之间进行上述处理,就可以完全绕过整个问题。

只需替换所有这些代码:

var format = "yyyy-MM-dd HH:mm:ss.fff";
var stringDate = DateTime.Now.ToString(format);
gl.LastUpdate =DateTime.ParseExact(stringDate,format,CultureInfo.InvariantCulture);

有了这个:

gl.LastUpdate = DateTime.Now;

【讨论】:

  • 这是我第一次编写代码时所做的。处理数据注释与流畅 api 的其他问题是问题所在,我会尽快将其指示为解决方案。
【解决方案3】:

我在我的模型上混合了数据注释和流利的 api。我只更改为数据注释,事情开始起作用了。显然,一个或多个流畅的 api 设置让 EF Core 感到困惑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多