Thursday, July 28, 2011
Wednesday, July 27, 2011
Getting SQL Server Date/Time usng LINQ to SQL
If you want to get the current date/time from your SQL Server (possibly to avoid different times between your server and the clients) using LINQ to SQL, you will find that there is no straight forward way of doing this.
Having had some trouble trying to accomplish this, I thought that it might be worth sharing how it can be done.
Note that this is extracted from Spyridon Spyriadis' blog as seen here
---
Using LINQ to SQL there is no way to get the time from the database built in the class. What you need to do is write your own code as the example below:
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;
using System.ComponentModel;
using System;
partial class dbGTOnlineDataContext
{
[Function(Name = "GetDate", IsComposable = true)]
public DateTime GetSystemDate()
{
MethodInfo mi = MethodBase.GetCurrentMethod() as MethodInfo;
return (DateTime)this.ExecuteMethodCall(this, mi, new object[] { }).ReturnValue;
}
}
Then anywhere in your code you can simple use the code below to get the time from the SQL Server database:
myDatabaseDataContext db = new myDatabaseDataContext();
DateTime dtNow = db.GetSystemDate();
Hope this helps...
Having had some trouble trying to accomplish this, I thought that it might be worth sharing how it can be done.
Note that this is extracted from Spyridon Spyriadis' blog as seen here
---
Using LINQ to SQL there is no way to get the time from the database built in the class. What you need to do is write your own code as the example below:
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;
using System.ComponentModel;
using System;
partial class dbGTOnlineDataContext
{
[Function(Name = "GetDate", IsComposable = true)]
public DateTime GetSystemDate()
{
MethodInfo mi = MethodBase.GetCurrentMethod() as MethodInfo;
return (DateTime)this.ExecuteMethodCall(this, mi, new object[] { }).ReturnValue;
}
}
Then anywhere in your code you can simple use the code below to get the time from the SQL Server database:
myDatabaseDataContext db = new myDatabaseDataContext();
DateTime dtNow = db.GetSystemDate();
Hope this helps...
Labels:
C#,
GetDate(),
LINQ,
SQL Server
Subscribe to:
Posts (Atom)