Thursday, July 27, 2017

Entity Framework: How to log SQL statements


In this blog, we will learn how to log the commands and SQL quries sent to database by EntityFramework. In Entity Framework, DBContext provides the DbContext.Database.Log property to log the SQL generated by DbContext.

Logging the generated SQL statement by entity framework always help to you to understand that how the entity framework are parsing the EF query and generating raw SQL statement and send to SQL engine to fetch records and  it helps you to tune EF query and improve system performance.

Here is an IQueryable EF query, which fetch the customer entity based on customer ID. We can use ToString() method to get the generated SQL statement.

IQueryable<Customer> query = _dbConext.Customers.Where(x => x.CustomerID == ID);
string sql = query.ToString();
Console.WriteLine(sql)

Output:

SELECT [Extent1].[CustomerID] AS [CustomerID], [Extent1].[CompanyName] AS [CompanyName]
FROM [dbo].[Customers] AS [Extent1]
WHERE [Extent1].[CustomerID] = @p0

In Entity Framework 6.0, there is a DbContext.Database.Log property, which used to setup delegate to log the commands and generated SQL queries sent to database by DBContext.

public Action<string> Log { get; set; }

Here is an example for logging EF activities to the console.

_dbConext.Database.Log = Console.Write;

IQueryable<Customer> query = _dbConext.Customers.Where(x => x.CustomerID == ID);

Other entity framework related posts:


No comments:

SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...