Over a million developers have joined DZone.

EF Feature CTP5: Raw SQL Query/Command Support

DZone's Guide to

EF Feature CTP5: Raw SQL Query/Command Support

· Database Zone
Free Resource

Whether you work in SQL Server Management Studio or Visual Studio, Redgate tools integrate with your existing infrastructure, enabling you to align DevOps for your applications with DevOps for your SQL Server databases. Discover true Database DevOps, brought to you in partnership with Redgate.

One of the new features that EF feature CTP5 supplies is the support for raw EF Feature CTP5: Raw SQL Query/Command SupportSQL Query/Command through the DbContext. In this post I’m going to show you examples for how you can use this feature. Pay attention that the details I provide might change in the future since its only a CTP and not a release.

DbContext Raw SQL Query/Command Support

EF feature CTP5 supports the execution of raw SQL queries and commands through the DbContext. This behavior resembles the ObjectContext’s same functionality that is exposed by the ExecuteStoreQuery<T> and ExecuteStoreCommand methods. You can use the DbContext's SqlQuery and SqlCommand methods which are exposed by the DbContext.Database property. The results of the method executions can be materialized into entities that can be tracked by the DbContext. Here is an example of how to use these methods: 

class Program
static void Main(string[] args)
using (SchoolEntities context = new SchoolEntities())
IEnumerable sqlQuery = context.Database.SqlQuery(typeof(Department), "select * from department");
foreach (Department item in sqlQuery)

sqlQuery = context.Database.SqlQuery(typeof(Course), "GetCoursesOrderByTitle");
foreach (Course item in sqlQuery)

var numberOfAffectedRows = context.Database.SqlCommand("DeleteDepartment @DepartmentID", new SqlParameter("DepartmentID", 8));
Console.WriteLine("Number of affected rows: {0}", numberOfAffectedRows);

In the program, that is using the same model from my previous example, I’m executing two queries (one is raw Sql and the other is using a stored procedure) and one command. The result of the execution:

Running Result


Lets sum up, the new CTP enables the running of raw Sql queries/commands. This can be very useful in scenarios that aren’t enabled by EF or advanced scenarios.

It’s easier than you think to extend DevOps practices to SQL Server with Redgate tools. Discover how to introduce true Database DevOps, brought to you in partnership with Redgate


Published at DZone with permission of Gil Fink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}