Generally, applications using .NET and EF Core use LINQ statements to interact with underlying database. In this article, let’s see some options which can be used to debugging those queries.
The database providers and framework converts the LINQ statements to the form which can be understood by the underlying database. This happens at execution time. So there can be various reasons why you would want to debug them.
Sometimes, the queries may not be performing as expected, causing delays in processing the requests. So, the reason can be to understand how to optimize those LINQ statements further.
Sometimes the queries may execute and return a resultset, which is not correctly bound to the EF core models defined in C# code. For example, the query might be returning
NULL for a column which is marked as
NON-NULL in C# code. In such cases, one of the way to resolve the issue quickly is to get the query which is being executed in underlying database and then check for values which cannot be bind to EF core models.
Now, that we have idea about why we would want to debug EF Core LINQ statements, let’s see how to debug those statements.
One of the way, I used in past was to use SQL Server profiler. If the application uses SQL Server database as underlying database, then SQL Server profiler can be used.
SQL Server Profiler is an interface to create and manage traces and analyze and replay trace results. Events are saved in a trace file that can later be analyzed or used to replay a specific series of steps when diagnosing a problem.
There are some other ways to provided by EF core 5.0. You can also create Interceptors or Diagnostic Listeners and then use logging to debug the EF core layer. You can refer documentation for more details about them.
Simple Logging is a feature that enables logging all queries to any place of your choice. I have demonstrated a demo in one of my previous posts.
In the remaining post, we are going to have a look at a simple feature Query Tags.
As the name suggests, it allows to add tags to the generated queries. The LINQ statements are converted to platform specific queries and if logging is enabled, platform specific queries may get logged to a store of your choice.
LINQ queries can be annotated with TagWith method. This method takes a string as input parameter. This string is written to the logs too just before the actual query traced. This tag can be useful to find something quickly in logs.
I hope you find this information helpful. Let me know your thoughts.
This Post Has One Comment
Pingback: The Code Blogger - How to troubleshoot performance issues in .NET EF Core Applications