Maksim Kruk
Maksim Kruk

Reputation: 1

How to add a date and time to a PostgreSQL database with EF?

I have a data model, with the help of EF migration I created a data table based on this model.

public class Event
{
    public int Id { get; set; }
    public string Theme { get; set; } = string.Empty;
    public string Description { get; set; } = string.Empty;
    public string Place { get; set; } = string.Empty;
}

After that, I remembered that I forgot to add the date and time field. I added this field and created a new migration, after which I applied the update database command.

public class Event
{
    public int Id { get; set; }
    public string Theme { get; set; } = string.Empty;
    public string Description { get; set; } = string.Empty;
    public DateTime EventTime { get; set; }
    public string Place { get; set; } = string.Empty;
}

When executing my request to update the date and time via the Web Api, I get the following error:

Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details. ---> System.InvalidCastException: Cannot write DateTime with Kind=Unspecified to PostgreSQL type 'timestamp with time zone', only UTC is supported. Note that it's not possible to mix DateTimes with different Kinds in an array/range. See the Npgsql.EnableLegacyTimestampBehavior AppContext switch to enable legacy behavior.

When executing my request to update the date and time via the Web Api, I get the following error. Before adding the date and time field, everything worked fine, with MSSQL everything also works fine and the date is added well.

Upvotes: 0

Views: 6107

Answers (1)

Artur
Artur

Reputation: 5530

Cannot write DateTime with Kind=Unspecified to PostgreSQL type 'timestamp with time zone', only UTC is supported

That means you need to convert your EventTime to UTC

Upvotes: 0

Related Questions