When you are writing LINQ queries against an Entity Framework context, you don’t have to worry about the SQL which is generated and executed. However, in some cases you may be interested in this SQL. It’s quite easy to switch on a logging mechanism which will be display all executed SQL in your Debug window. You have to provide an Action to the DbContext.Database.Log
property. You provide a lambda with the functionality you want. If you want you can log this output also to a file or for example the Clipboard.
Imports System.Data.Entity Module MainModule Private ReadOnly MyContext As New MyContext Sub Main() MyContext.Database.Log = Sub(x) Debug.WriteLine(x) End Sub Dim result = MyContext.Patients.Include(Function(x) x.Dossiers). Select(Function(x) New With {.PatientId = x.PatientID, .LastName = x.LastName, .DossierCount = x.Dossiers.Count}).ToList() End Sub End Module
In this case, where I want to list a couple of properties of a Patient
in combination of the number of related Dossiers
, you will see the following SQL in the Debug Window.
SELECT [Extent1].[PatientID] AS [PatientID], [Extent1].[LastName] AS [LastName], (SELECT COUNT(1) AS [A1] FROM [dbo].[Dossier] AS [Extent2] WHERE [Extent1].[PatientID] = [Extent2].[PatientID]) AS [C1] FROM [dbo].[Patient] AS [Extent1]
Leave a Reply
You must be logged in to post a comment.