1

I want to execute custom query to get datetime of DB server select Getdate() using entity framework. How can I do this?

Thanks

3
  • stackoverflow.com/questions/200617/… The second answer. Commented Jul 14, 2010 at 12:58
  • I am using Entity Framework, rather LINQ. this is for LINQ Commented Jul 14, 2010 at 13:01
  • What's your DB provider? MS SQL Server? MySQL? Oracle? ... Commented Jul 14, 2010 at 13:37

3 Answers 3

4
ObjectQuery<DateTime> date = new ObjectQuery<DateTime>("select Getdate()", context)
DateTime now = date.Single();
Sign up to request clarification or add additional context in comments.

1 Comment

I am getting this exception "The query syntax is not valid."
2

You can try somethink like that :

public static partial class ObjectContextExtension
{
    public static T ExecuteScalarCommand<T>(this ObjectContext context, string command)
    {
        DbConnection connection = ((EntityConnection)context.Connection).StoreConnection;
        if (connection.State == ConnectionState.Closed)
            connection.Open();

        DbCommand cmd = connection.CreateCommand();
        cmd.CommandText = command;
        cmd.CommandType = CommandType.Text;

        return (T)cmd.ExecuteScalar();
    }

It add the method "ExecuteScalarCommand" to the ObjectContext.
You just give the SQL request as parameter and the return type for the generic type.

Comments

-1
Public Function GetDateTimeFromServer() As DateTime
    Using context As New NorthwindEntities()
        Dim dateQry As IQueryable(Of DateTime) = From bogus In context.Products_
            Select DateTime.Now
        Dim result As DateTime = dateQry.First()
        Return result
    End Using
End Function

You can use a query against a table (e.g. Products) and make sure you don't select any columns in the table as shown in the above code. It is not elegant but it works.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.