✅ EF does not put datetimes properly to the datebase
I am writing a backend app in asp.net core. This is my service code :
But in the database they are saved as
infinity
:28 Replies
1. Don't use
AddAsync
2. Use a DTO, don't receive or send database models directly into/from an API
3. What is BeforeSave()
?
Also, use DateTime.Now
using DateTime.Now gives error
Angius
REPL Result: Success
Result: <>f__AnonymousType0#1<DateTime, DateTime>
Compile: 254.013ms | Execution: 53.787ms | React with ❌ to remove this embed.
What is the error?
Cannot write DateTime with Kind=Local to PostgreSQL type 'timestamp with time zone', only UTC is supported.
What is your
Note
model?
Does it actually use datetime?Do you use code-first or db-first?
what does it mean?
Do you create data models and use migrations to modify the database?
Or do you modify the database and scaffold the data models?
i think i use codefirst
Aight
Try
DateTime.UtcNow
also why should i not use AddAsync
Because it's only useful for some very specific edge cases
Asynchronous code is used when any sort of IO happens
i only use the code above
In case of the database,
SaveChangesAsync()
does the IO
.Add()
only impacts the change tracker
So it doesn't need to be asyncokay
?
this is the command that is executed for inserting
Yeah, and?
should i do anything so that it converts datetime to database type?
No, that would defeat the purpose of an ORM like EF
yeah
Did you try
DateTime.UtcNow
like I suggested?no i did not see it. let me try it
DateTimeOffset.Now
should also work according to this stack thread with the same issue: https://stackoverflow.com/questions/73693917/net-postgres-ef-core-cannot-write-datetime-with-kind-local-to-postgresql-typeStack Overflow
.net postgres EF core Cannot write DateTime with Kind=Local to Post...
I have a .Net6 console app that uses nuget packages:
"Microsoft.EntityFrameworkCore, Version 6.0.8"
"Npgsql.EntityFrameworkCore.PostgreSQL, Version 6.0.6"
"Npgsql, Version...
Yeah it worked !
thanks
Yeah, it has to do with datetime handling they improved in some version of NpgSQL