Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use SQL's GETDATE() and DATEADD() in a Linq to SQL expression?

If I have a Linq to SQL expression like this:

  from subscription in dbContext.Subscriptions  where subscription.Expires > DateTime.Now select subscription 

I want this to to use the SQL Servers GETDATE() function instead of the time of the machine running the C# program.

The next question would be how to translate this:

DateTime.Now.AddDays(2) 

to this:

DATEADD(dd, 2, GETDATE()) 
like image 845
Thomas Jespersen Avatar asked Oct 14 '08 10:10

Thomas Jespersen


People also ask

How can add date to Getdate in SQL?

SQL Server DATEADD() Function The DATEADD() function adds a time/date interval to a date and then returns the date.

How does the Dateadd function work in SQL?

The DATEADD() function adds a number to a specified date part of an input date and returns the modified value. The DATEADD() function accepts three arguments: date_part is the part of date to which the DATEADD() function will add the value .

How can I get 30 days from current date in SQL?

SELECT (column name) FROM (table name) WHERE (column name) < DATEADD(Day,-30,GETDATE()); Example.


1 Answers

Try this:

[Function(Name="GetDate", IsComposable=true)]   public DateTime GetSystemDate()   {        MethodInfo mi = MethodBase.GetCurrentMethod() as MethodInfo;        return (DateTime)this.ExecuteMethodCall(this, mi, new object[]{}).ReturnValue;   } 

EDIT: this needs to be a part of your DataContext class.

Now you can use GetSystemDate() instead of DateTime.Now in your queries. As for date differences take a look at System.Data.Linq.SqlClient namespace, especially DayDiffXXX functions of SqlMethods class.

like image 117
liggett78 Avatar answered Oct 05 '22 21:10

liggett78