简体   繁体   中英

Executing Custom query — Entity Framework

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

Thanks

ObjectQuery<DateTime> date = new ObjectQuery<DateTime>("select Getdate()", context)
DateTime now = date.Single();

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.

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 (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM