Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to get the current time of sql server? #4362

Closed
linqingfeng opened this issue Jan 21, 2016 · 5 comments
Closed

How to get the current time of sql server? #4362

linqingfeng opened this issue Jan 21, 2016 · 5 comments

Comments

@linqingfeng
Copy link

Hi,

In EF6, we get sql server current time, like this

DateTime currentDateTime = db.Database.SqlQuery ("SELECT GETDATE ();"). FirstOrDefault ();

But EF7, Database.SqlQuery does not exist, how to solve?

[Notes]

We can not use the following code:

DateTime currentDateTime = db.Users.Select (q => DateTime.Now) .FirstOrDefault ();

or

DateTime currentDateTime = db.Set () Select (q => DateTime.Now) .FirstOrDefault ().;

Since the beginning of our DbContext not contain any Entity, so ...how to solve?

thank you very much!

@rowanmiller
Copy link
Contributor

Until we have the ability to query for non-entity results (tracked by #1862) you would need to write something like this.

var con = db.Database.GetDbConnection();
var cmd = con.CreateCommand();
cmd.CommandText = "SELECT GETDATE()";
con.Open();
var datetime = (DateTime)cmd.ExecuteScalar();
con.Close();

@rowanmiller
Copy link
Contributor

Closing this out as I think that answers your question and we already have #1862 tracking the feature that you really want in order to do this cleanly. Feel free to re-open if you disagree 😄.

@AndriySvyryd
Copy link
Member

As a side note it is highly suggested to use UTC time instead of the local time by using GETUTCDATE to avoid having to deal with time zones, daylight savings time and so on.

@linqingfeng
Copy link
Author

Thank you very much!

@mohammadfiroozi
Copy link

mohammadfiroozi commented Jan 9, 2019

DataTime getServerTime = context.CreateQuery<DateTime>("CurrentDateTime()").AsEnumerable().FirstOrDefault();

@ajcvickers ajcvickers reopened this Oct 16, 2022
@ajcvickers ajcvickers closed this as not planned Won't fix, can't repro, duplicate, stale Oct 16, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants