db.database.ExecuteSQLCommand equivalent in EF 7

asp.net-core asp.net-core-mvc entity-framework entity-framework-core

Question

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.

Accepted Answer

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.


Popular Answer

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



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why