Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ask the database server for current datetime using entity framework?

I have an entity with a ModifiedDateTime property which I want to be updated with the current datetime from the database instead of the "application" server executing the application.

Every time I want to update or add a person to my datebase on SQL Server 2008 I want to fill ModifiedDateTime filed. It's not like I can change update query as with data adapter command when I work with dataset and to define for my ModifiedDateTime filed to be GetDate(). I created stored function to return me a value of GetDate() method, but I have a problem to import procedure which returns values as int, string or no value at all, already just entity values as Person for example in my case. Why is that?

Anyway, it would be of great help if you can help me to retrieve the current DateTime from the database server.

like image 590
Levelbit Avatar asked Apr 06 '10 13:04

Levelbit


3 Answers

Is there a reason you just can't push it down to your database? If you include DateTime.Now in your entity query, it will push it down (getdate) to the database.

Example linq to entities

 var dQuery = dbContext.CreateQuery<DateTime>("CurrentDateTime() ");
 DateTime dbDate = dQuery.AsEnumerable().First();

SQL Generated ..

SELECT GetDate() AS [C1] FROM  ( SELECT cast(1 as bit) AS X ) AS [SingleRowTable1]

Might be a better way to do it ?

like image 140
Nix Avatar answered Sep 24 '22 18:09

Nix


This is an update of @Nix response to EF4:

var dateQuery = dbContext.Database.SqlQuery<DateTime>("SELECT getdate()");
DateTime serverDate = dateQuery.AsEnumerable().First();
like image 37
Rodrigo Avatar answered Sep 23 '22 18:09

Rodrigo


An update for .net core 2.0

var dual =  databaseContext
            .Set<Dual>()
            .FromSql("SELECT -1 AS Id, GETDATE() AS DateTime")
            .First();

The fake entity

public class Dual
{
    public int Id { get; set; }
    public DateTime DateTime { get; set; }
}
like image 22
user823959 Avatar answered Sep 23 '22 18:09

user823959