Join the Stack Overflow Community
Stack Overflow is a community of 6.2 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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?

share|improve this question
    
Is dbContext properly initialized as Entities? – James Joyce Alano Feb 10 at 2:32
    
@MatchesMalone Yes, normal LINQ queries working properly – Obin Feb 10 at 2:37
    
see my answer below on how to use an extension method to use parameterized (or not) SQL. – iberodev Feb 10 at 2:39
up vote 9 down vote accepted

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);
share|improve this answer
    
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 at 2:54
    
@iberodev How would you do it if your sql query contains two tables? – nam Sep 14 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 – iberodev Sep 14 at 22:57

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.