12

I migrate my application to ASP.NET MVC Core and Entity Framework Core and i found problem. I have raw SQL query to entity like this

var rawSQL = dbContext.Database.SqlQuery<SomeModel>("Raw SQL Query").ToList();

But there is no SqlQuery<T> in context.Database. Do you have solution for this problem?

Obin
  • 473
  • 2
  • 6
  • 13

1 Answers1

12

Make sure you add using Microsoft.Data.Entity; because there is an extension method you could use.

var rawSQL = dbContext.SomeModels.FromSql("your SQL");

Even better, instead using raw SQL (at risk of SQL injections attacks) this FromSql method allows you to use parameterized queries like:

dbContext.SomeModels.FromSql("SELECT * FROM dbo.Blogs WHERE Name = @p0", blogName);
diegosasw
  • 13,734
  • 16
  • 95
  • 159
  • 1
    Working well but its strange calling SQL queries from specific entity model than generally database. About injections attacks i know and i'm using SQL parameters but i wanted to show simple problem in example. Thanks – Obin Feb 10 '16 at 02:54
  • @iberodev How would you do it if your sql query contains two tables? – nam Sep 14 '16 at 22:41
  • @nam as shown here: https://docs.efproject.net/en/latest/querying/raw-sql.html#composing-with-linq by adding an `.Include(b => b.Posts)` you are joining with another table – diegosasw Sep 14 '16 at 22:57
  • 2
    Just a note, for Entity Framework Core, I had to include the namespace: using Microsoft.EntityFrameworkCore; – Reynier Booysen Jan 30 '17 at 13:07
  • 2
    what about querying against `DbContext` instead of `DeSet`? @iberodev – ManirajSS Sep 15 '17 at 13:41