Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raw SQL queries and Entity Framework Core

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?

like image 736
Obin Avatar asked Feb 10 '16 02:02

Obin


People also ask

How use raw SQL query in Entity Framework Core?

Entity Framework Core provides the DbSet. FromSql() method to execute raw SQL queries for the underlying database and get the results as entity objects. The following example demonstrates executing a raw SQL query to MS SQL Server database. var context = new SchoolContext(); var students = context.

What is raw SQL queries?

Raw SQL, sometimes also called native SQL, is the most basic, most low-level form of database interaction. You tell the database what to do in the language of the database. Most developers should know basics of SQL. This means how to CREATE tables and views, how to SELECT and JOIN data, how to UPDATE and DELETE data.


1 Answers

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);
like image 56
diegosasw Avatar answered Oct 22 '22 02:10

diegosasw