tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

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

14 Nov 2012 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; }
}