1

I have a DataContext instance that I want to use to execute raw SQL (if possible). I remember that "regular" EntityFramework 6 can do this (https://msdn.microsoft.com/en-us/library/bb361109(v=vs.110).aspx) but I can't find any method on the one in Core. I've heard of the FromSql extension method (https://learn.microsoft.com/en-us/ef/core/querying/raw-sql) but that doesn't show up when do myContext.myTable.

Below are the references I have (image because I'm too lazy to type them out).

enter image description here

2
  • 1
    Please use correct tags in future. Your question is related to EntityFramework Core (that's where the DbContext comes from) and not to ASP.NET or ASP.NET core, since "in old ASP.NET" is just plain wrong. You can also use EF6 (the "old" EntityFramework) in ASP.NET Core if you target the full .NET Framework Commented Apr 20, 2017 at 7:26
  • Your references look fine. Can we see the using directives in your file? A simple using Microsoft.EntityFrameworkCore; should do the trick to get you the FromSql() call. Commented Apr 20, 2017 at 12:53

1 Answer 1

1

I realise that this is an old question, but here are some answers anyway.

You have 2 options, depending on what you are trying to do:

Option 1: DbSet FromSql

using Microsoft.EntityFrameworkCore;
...
var sql = "select * from clients";
var clients = _clientDbContext.Clients.FromSql(sql);

Note that this requires you to have a Client entity matching the output of the sql statement and the related DbSet defined on your DbContext implemementation.

Option 2: Raw data access

using (var conn = (SqlConnection)((DbContext)_clientDbContext).Database.GetDbConnection())
{
    conn.Open();
    using (var reader = new SqlCommand(sql, conn).ExecuteReader())
    {
        ...
    }
    conn.Close();
}

Now you have access to the raw DbConnection and the ADO.NET world and can use SqlCommand, DataTables etc to run any SQL and manage the data returned yourself.

I would caution you against mixing Entity Framework and direct SQL database updates - but this can be useful for picking up a small piece of data - maybe a config value, or running a stored procedure.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.