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?

3
  • Is dbContext properly initialized as Entities?CommentedFeb 10, 2016 at 2:32
  • @MatchesMalone Yes, normal LINQ queries working properly
    – Obin
    CommentedFeb 10, 2016 at 2:37
  • see my answer below on how to use an extension method to use parameterized (or not) SQL.
    – diegosasw
    CommentedFeb 10, 2016 at 2:39

1 Answer 1

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); 
5
  • 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
    CommentedFeb 10, 2016 at 2:54
  • @iberodev How would you do it if your sql query contains two tables?
    – nam
    CommentedSep 14, 2016 at 22:41
  • @nam as shown here: docs.efproject.net/en/latest/querying/… by adding an .Include(b => b.Posts) you are joining with another table
    – diegosasw
    CommentedSep 14, 2016 at 22:57
  • 2
    Just a note, for Entity Framework Core, I had to include the namespace: using Microsoft.EntityFrameworkCore;CommentedJan 30, 2017 at 13:07
  • 2
    what about querying against DbContext instead of DeSet? @iberodev
    – ManirajSS
    CommentedSep 15, 2017 at 13:41

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.