Making Entity Framework generate SQL with column=GetUtcDate()
Our app runs on many web servers. The time of these web servers can get
skewed over time, as is to be expected. The database is a single separate
machine with it's own time. We're using EF 5.0 and have a table that needs
very precise and consistent times in multiple columns. I would like to be
sure the date columns in this table always use the database servers time.
In SQL I would just set the column to GetUtcDate(). Simple, the date is
computed and set on the database server, done. But how can I do this with
EF on an insert or update? To be clear I need the SQL generated by EF to
set the column to the function GetUtcDate() so that the value comes from
the database server. I do not want the date being calculated on the web
server. Some ideas I've seen and considered and why they don't work for
me:
1) I could use default values on the columns in the schema. But I have
many update scenarios where I also need consistent dates, not just
inserts. 2) I could use triggers in the database. But we currently have
zero logic in our database (we are using an ORM after all) and I don't
want to set that precedent if I can avoid it. It also is tricky to
determine when to update these columns on the database end. 3) I can get
the database server time manually (separate query as in the example
below), set the column to that value, then do the update. But this is very
inefficient as it requires an extra call to the database. In a tight loop
this is way too much overhead. Plus the time is now less accurate since I
got the time milliseconds earlier, though it is at least consistent.
CreateQuery<DateTime>("CurrentUtcDateTime()").Execute().First();
So what is the right way to do this? Or is it even possible to make EF do
the right thing here?
No comments:
Post a Comment