Monday, July 19, 2010

Executing SQLQueries on ObjectContext

Recently I worked with the entity framework (3.5) and at some point I had the need to execute a custom SQL command. Fortunately does the object context provide the underlying DBConnection and with that you can simply execute SQLCommands.

I read on the Internet that the new Version (4.0) has already integrated something similar.

This is an extension Method that I wrote which makes it easy to execute these queries:


public static void ExecuteSQL(this ObjectContext context, string sql)
{
var connection = context.Connection;
var command = connection.CreateCommand();
command.CommandText = sql;

try
{
connection.Open();
command.ExecuteNonQuery();
}
finally
{
connection.Close();
}
}

No comments: