tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

How to show SQL command created by Entity Framework? [2012 edition]

14 Nov 2012 1 mins Entity Framework, LINQ

Four years back (wow) I wrote a post about how to show SQL command created by Entity Framework. The information there still holds. But now it’s 2012, Entity Framework progressed. Now you’re probably using DbContext and IDbSet<T> APIs, it’s actually recommended.

There you don’t have the ObjectQuery. As the new API is simpler and more focused, also getting the command is simple. Simply call ToString() method and you’re done.

class Program
{
	static void Main(string[] args)
	{
		Database.SetInitializer<MyContext>(null);
		using (var ctx = new MyContext())
		{
			Console.WriteLine(ctx.FooBars.Where(x => x.Id == -1).ToString());
		}
	}
}
class MyContext : DbContext
{
	public IDbSet<FooBar> FooBars { get; set; }
}
class FooBar
{
	public int Id { get; set; }
	public string Baz { get; set; }
}

Profile Picture Jiří Činčura is .NET, C# and Firebird expert. He focuses on data and business layers, language constructs, parallelism, databases and performance. For almost two decades he contributes to open-source, i.e. FirebirdClient. He works as a senior software engineer for Microsoft. Frequent speaker and blogger at www.tabsoverspaces.com.