FormatException: The string was not recognized as a valid DateTime. There is an unknown word starting at index 0

c# entity-framework-core

Question

I have spent 4 days trying to get EF Core to save a datetime value for a record. It keeps failing with the following error:

FormatException: The string was not recognized as a valid DateTime. There is an unknown word starting at index 0.

I have looked at almost a hundred posts regarding something similar to no avail. I've tried multiple datetime formats. Below is a link to the latest attempt in Visual Studio with some watches set for pertinent values.

    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; }

I attempted to find documentation for the datetime format that EF Core is expecting with no success.

I can't save my record because of this error. I assume it has to be something relatively simple and hope that someone can shed some light on this.

Exception Details

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 parameterValues, Boolean closeConnection) at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, 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 parameters) at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](Func2 operation, Func2 verifySucceeded, TState state) at 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()

1
3
6/15/2017 12:44:34 PM

Accepted Answer

I was mixing data annotations and fluent api on my model. I changed to data annotations only and things started working. Apparently one or more of the fluent api settings was confusing EF Core.

0
6/15/2017 1:25:30 PM

Popular Answer

The reason here is that you're converting your DateTime value to a string and then try to parse it back to a DateTime, and you specify a culture for the parsing but not for the formatting.

So either pass a culture to the ToString method, or remove it from the parsing...

However, the entire problem can be bypassed entirely by just not doing the above juggling between strings and DateTime values.

Simply replace all this code:

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

With this:

gl.LastUpdate = DateTime.Now;


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow