NicoJuicy
NicoJuicy

Reputation: 3528

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.

Upvotes: 9

Views: 8005

Answers (2)

Matt Sanders
Matt Sanders

Reputation: 983

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");

Upvotes: 7

bricelam
bricelam

Reputation: 30345

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.

Upvotes: 8

Related Questions