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.

1
8
5/26/2015 10:48:52 PM

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.

8
5/28/2015 10:54:09 PM

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


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow