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? Commented Feb 10, 2016 at 2:32
  • @MatchesMalone Yes, normal LINQ queries working properly Commented Feb 10, 2016 at 2:37
  • see my answer below on how to use an extension method to use parameterized (or not) SQL. Commented Feb 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);
Sign up to request clarification or add additional context in comments.

5 Comments

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
@iberodev How would you do it if your sql query contains two tables?
@nam as shown here: docs.efproject.net/en/latest/querying/… by adding an .Include(b => b.Posts) you are joining with another table
Just a note, for Entity Framework Core, I had to include the namespace: using Microsoft.EntityFrameworkCore;
what about querying against DbContext instead of DeSet? @iberodev

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.