Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute RAW SQL on DbContext in EF Core 2.1

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?

like image 329
J86 Avatar asked Nov 28 '18 10:11

J86


1 Answers

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))
like image 56
Thom Kiesewetter Avatar answered Sep 28 '22 09:09

Thom Kiesewetter