6

What is the alternate for GETDATE() in LINQ?

I got some workaround from the following post:

Is there any better approach? In which, there is no need to an ExecuteQuery or a separate function call?

Community
  • 1
  • 1
Bisileesh
  • 1,982
  • 2
  • 19
  • 29

3 Answers3

11

As far as I can see with linq to sql the post you refer to is the way to go. I don't see how anything could be better. It's a pretty elegant solution.

With Entity Framework there is a possibility to use SqlFunctions.CurrentTimestamp. Besides that, even when you use DateTime.Now in linq to entities (not linq to sql) it is translated to GetDate:

context.Companies.Select (c => DateTime.Now);

translates:

SELECT 
GetDate() AS [C1]
FROM [dbo].[Company] AS [Extent1]

It's a different story if you only want to get the database date. In that case I don't see how anything could beat executing a query SELECT GetDate().

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
0

FROM VB

Private Function GetServerDate() As DateTime

    Using context As New DirectEDISQLEntities
 Dim Query = context.Reports_MailList.[Select](Function(c) DateTime.Now).FirstOrDefault
        Return Query
    End Using

End Function

And equal to

SELECT SysDateTime() AS [C1] FROM [dbo].[Reports_MailList] AS [Extent1]

sansalk
  • 4,595
  • 2
  • 36
  • 37
0

You can try this:

using (DataContext dboContext = new DataContext())
                {
                    var dQuery = dboContext.Database.SqlQuery<DateTime>("SELECT getdate()");
                    return dQuery.AsEnumerable().First();
                }
Joe
  • 349
  • 2
  • 3