Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

db.database.ExecuteSQLCommand equivalent in EF 7

Whats the equivalent of

db.Database.ExecuteSqlCommand(Sql.ToString());

in Entity Framework 7? I saw .FromSQL() in beta 4, but haven't seen anything to the above.

like image 295
NicoJuicy Avatar asked May 26 '15 22:05

NicoJuicy


2 Answers

The feature isn't implemented yet. Track its progress using issue #624. Here is a crude extension method you can use for now.

public static int ExecuteSqlCommand(this RelationalDatabase database, string sql)
{
    var connection = database.Connection;
    var command = connection .DbConnection.CreateCommand();
    command.CommandText = sql;

    try
    {
        connection.Open();

        return command.ExecuteNonQuery();
    }
    finally
    {
        connection.Close();
    }
}

Use it like this:

db.Database.AsRelational().ExecuteSqlCommand("EXEC MySproc");

Note, this doesn't take into account any active transaction.

like image 118
bricelam Avatar answered Sep 30 '22 17:09

bricelam


Just wanted to provide an update of the latest way to use this with for Entity Framework Core RC1.

There is an extentsion on the DatabaseFacade class in the Microsoft.Data.Entity namespace that you can use as follows:

_dbContext.Database.ExecuteSqlCommand("EXEC MySproc");
like image 40
Matt Sanders Avatar answered Sep 30 '22 17:09

Matt Sanders