Learning Querying in Entity Framwork – Tips 1

Learning to write queries in Entity Framework is key to leverage the benefits provided by Entity Framework.

Some utilities which can help us on the journey are:

  • Object Dumper
  • Printing the SQL generated by Entity Framework

Object Dumper

This is the Microsoft utility to dump result of linq queries as an object graph. This is a great utility to see the results from a linq query. We can use object dumper to print out the results of query from Entity Framework to console. In case you want to see the output in a single file, call the method which has the Entity Framework query from a MsTest test case. There is a TestContext property which can capture the console output which can be viewed in the test results pane of MS Test.

Dumping SQL Query generated by Entity Framework

Entity Framework 6 has a neat utility to print the SQL generated by Entity Framework for the query given. Just call ToString on the variable containing the query. This will print the SQL generated to the console.

The above 2 utilities are of great help while learning querying in Entity Framework.

A sample code listing using the above two tips is given below:

public void GetCustomerMini()
            using (var context = new AWEntities())
                var query = from c in context.Customers select new {c.CustomerID, c.FirstName, c.LastName};
                var customer = query.ToList();
                var sql = query.ToString();
                Console.WriteLine("SQL: {0}", sql);
                Console.WriteLine("Count: {0}", customer.Count());

you can call the above method in MSTest test method and using TextContext property have the console output captured as part of test result.

Linqpad can also make this simpler. But for people who like visual studio the above 2 utilities are of great help