C# – the equivalent of LINQ-to-SQL’s ExecuteCommand in Entity Framework

centity-frameworklinq-to-sql

I am porting an application running on LINQ-to-SQL to Entity Framework, and am having trouble finding an equivalent to ExecuteCommand:

db.ExecuteCommand("INSERT Infos (Title) VALUES ('this is an added title')");

I found this site which tells me that it is possible to implement ExecuteCommand as an extension method on your ObjectContext, leaving the existing code unchanged by adding this code to a static method in your project:

public static int ExecuteCommand(this ObjectContext objectContext,
                                string command) {
    DbConnection connection = ((EntityConnection)objectContext.Connection).StoreConnection;
    bool opening = (connection.State == ConnectionState.Closed);
    if (opening)
        connection.Open();

    DbCommand cmd = connection.CreateCommand();
    cmd.CommandText = command;
    cmd.CommandType = CommandType.StoredProcedure;
    try {
        return cmd.ExecuteNonQuery();
    }
    finally {
        if (opening && connection.State == ConnectionState.Open)
            connection.Close();
    }
}

But I've tried putting it (1) in the class where I use it, (2) in the Entity generated class file, (3) in a static class in the project, but always get various errors. Where do I need to put this method exactly?

The above site also said:

ExecuteCommand is being considered as
an enhancement for a future release of
the Entity Framework

Does ExecuteCommand() exist in the newest version of Entity Framework? I am using the Entity Framework that was installed with Visual Studio 2008 SP1.

Best Answer

.NET Framework 4's ObjectContext class has the ExecuteStoreCommand and ExecuteStoreQuery methods that seem to be what you are looking for.