0

I am encountering an issue while executing the SaveChanges() method in a background job in a .NET 6 Web API project. The code snippet below illustrates the scenario:

public bool UpdateServices()
{
    var activeServices = _context.services
                            .AsNoTracking()
                            .Where(service => service.active)
                            .ToList();

    foreach (var service in activeServices)
    {
        var server = _context.servers.FirstOrDefault(server => server.id == service.server_id && server.active);
        if (server != null)
        {
            service.status = 1;
            service.updated_at = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Utc);
        }
        _context.services.Update(service);
    }
    _context.SaveChanges();
    return true;
}

However, during execution, I encounter the following exception at _context.SaveChanges():

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, or multirange. (Parameter 'value')

The underlying database is PostgreSQL, and the field updated_at is of type timestamp without time zone.

How can I resolve this issue and ensure that the DateTime values are correctly handled for PostgreSQL in this context?

1 Answer 1

1

I saw this problem being resolved in other posts maybe the answers to these posts can help you:

  • In this first post_1 he follows a path to adjust the database configuration, basically uses "EnableLegacyTimestampBehavior" defining it in AppContext.SetSwitch().

  • In this second post_2 follows an implementation in the code to handle the DateTime before, so it creates an extention method SetKindUtc() to control the DateTime.

I hope I helped you find the solution to this error!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.