.NET CORE 2.1.1 with Entity Framework Core 2.1.4 Code First: Conversion failed when converting date and/or time from character string

.net-core asp.net asp.net-core ef-migrations entity-framework-core

Question

I have a Extension Method to seed my table after created:

public static class ModelBuilderExtensions
{
    public static void Seed(this ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<AppUser>(entity =>
        {
            entity.HasData(
                new Event() { id = 1, WhenDate = DateTime.Now.AddMonths(1) }
            )
    }
}

I created migration file with this command

Add-Migration InitialCreate

and then

Update-Database

to create database with table but I have this error:

Conversion failed when converting date and/or time from character string

in my InitialCreate file I have this line:

WhenDate = table.Column(type: "datetime", nullable: false)

in my console log, in insert into command, I see this character string:

'2019-03-12T16:09:33.617+01:00'

I guess the string format is not correct, but how to change it? And what is the right format?

Thanks

1
1
2/12/2019 4:16:25 PM

Accepted Answer

I found a solution, if I replace Now by UtcNow it works ! Because it remove "+01:00"...

replace

DateTime.Now.AddMonths(1)

by

DateTime.UtcNow.AddMonths(1)

string result:

'2019-03-12T17:08:25.682Z'

0
2/12/2019 5:21:29 PM

Popular Answer

For me, this occurs when I tried to alter column after running update-database:

I fixed by added manual default value like: defaultValue:"0001-01-01"

For example:

  migrationBuilder.AddColumn<DateTime>(
                name: "OperationDateTime",
                schema: "DefinitionContext",
                table: "Path",
                type: "DateTime",
                nullable: false,
                defaultValue:"0001-01-01");


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