I have researched this and always found examples like this:
var blogs = context.Blogs
.FromSql("SELECT * FROM dbo.Blogs")
.ToList();
The problem is, I don't want to run my raw SQL on the Blogs table. Basically, I want to implement an interface like this:
bool ExecuteNonSafeSql(
string connectionString,
string sql);
Is there a way to do that with DbContext?
You can use context.Database.ExecuteSqlCommand()
to execute sql.
If you want to use SqlCommand
you can get the connection by
var cnn = (SqlConnection) context.Database.GetDbConnection();
cnn.Open();
using (var cmd = new SqlCommand(sql, cnn))
using (var rdr = cmd.ExecuteReader(CommandBehavior.SingleResult))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With