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

I spent 4 days trying to get EF Core to store the datetime value for writing. 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 through almost a hundred posts about something like this to no avail. I have tried several datetime formats. Below is a link to a recent try in Visual Studio with some hours set to the appropriate 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 tried to find documentation on the datetime format that EF Core expects without success.

I am unable to save my entry due to this error. I guess this should 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, IReadOnlyDictionary

2 Values, boolean closeConnection) to Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader (IRelationalConnection connection, IReadOnlyDictionary 2 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(Tuple

2 parameters) to Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecuteStrate [Functions] 2 operation, Func

. ) in 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()

+3


source to share


3 answers


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



0


source


Change the second line. You cannot use a prefixed format string {0:

in a call to the ToString method:



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

      

+1


source


The reason here is that you are converting the value DateTime

to a string and then trying to parse it back to the DateTime and you are defining a culture for parsing but not formatting.

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

However , the entire problem can be completely circumvented by not performing the specified movement between strings and DateTime values.

Just 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);

      

Wherein:

gl.LastUpdate = DateTime.Now;

      

+1


source







All Articles