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.
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.
Entity Framework Core provides the DbSet. FromSql() method to execute raw SQL queries for the underlying database and get the results as entity objects.
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");
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With