Raw SQL queries and Entity Framework Core

asp.net-core asp.net-core-mvc c# entity-framework-core

Question

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?

1
12
2/10/2016 2:37:36 AM

Accepted Answer

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);
12
2/10/2016 2:37:26 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow