Using Entity Framework to run a custom query

c# entity-framework winforms

Question

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

Thanks

1
1
7/14/2010 12:54:07 PM

Accepted Answer

ObjectQuery<DateTime> date = new ObjectQuery<DateTime>("select Getdate()", context)
DateTime now = date.Single();
4
3/5/2012 3:08:44 PM

Popular Answer

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.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow