Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to execute custom SQL query using EF7

I decided to move one of my projects to Entity Framework 7 (rc1-final). I am targeting SQL Server and EntityFramework.MicrosoftSqlServer package is also installed.

I have only one problem: it seems like I can't execute custom SQL query in order to fetch some objects from DB.

DatabaseFacade object (which can be accessed via DbContext.Database property) provides an extension method ExecuteSqlCommand (that returns nothing), But it does not provide SqlQuery<T> method that allows to fetch objects. Both methods were available in good old EF 6, but new EF 7 declares only first one.

So, is SqlQuery<T> method still here (but moved/renamed) or it was entirely removed from new EF implementation?

Of course it is absolutely possible to solve it in a verbose way (using SqlCommand and its ExecuteReader method) but I prefer to avoid it.

like image 679
rtf_leg Avatar asked Dec 17 '15 05:12

rtf_leg


People also ask

How use raw SQL query in Entity Framework Core?

Entity Framework Core allows you to drop down to raw SQL queries when working with a relational database. Raw SQL queries are useful if the query you want can't be expressed using LINQ. Raw SQL queries are also used if using a LINQ query is resulting in an inefficient SQL query.

Which of the following method is used to execute the raw SQL query to the database in EF 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.


2 Answers

EntityFramework.Relational exposes the following extension method;

public static IQueryable<TEntity> FromSql<TEntity>(
        [NotNull] this IQueryable<TEntity> source,
        [NotNull] [NotParameterized] string sql,
        [NotNull] params object[] parameters)
        where TEntity : class

So you can do this;

myDatabaseContext.Customers.FromSql("SELECT * FROM Customers WHERE Name='p0'", "timothy");
like image 56
Stafford Williams Avatar answered Nov 14 '22 21:11

Stafford Williams


To execute a custome SQL query in EF7, you can create a "fake" table which structure like structure of your SQL query returns.

Example: Your query is: "select a.A, b.B from A,B where a.b_id=b.id". The fake table will contain 2 column like A,B. In your program, you can do this:

var result = myDatabaseContext.FakeTables.FromSql("select a.A, b.B from A,B where a.b_id=b.id");
like image 40
Hong Thanh Avatar answered Nov 14 '22 21:11

Hong Thanh