Loupe - Log - Monitor - Resolve
Loupe / Developer's Guide / For .NET Core / 6 / 8 / For EF Core / Using Loupe with Entity Framework - Tracing Actions
In This Topic
    Using Loupe with Entity Framework - Tracing Actions
    In This Topic

    If you're using Entity Framework 6 or later for data access you'll want to add the Loupe Agent for Entity Framework which automatically records log entries and metrics for EF actions. 

     Inspecting an Entity Framework Action

    Every EF call records at least two things – a performance metric and a log statement at the start of execution.  If the call throws an exception you’ll also get a message at the end with the result information (logged as a warning so it’ll show up as a Loupe Application Event).

    When recording an EF Action the following is automatically captured:

    • Summary: A short version of the SQL Statement executed (when the statement is too long to start with the entire statement)
    • Full Statement: The exact, complete SQL Statement that was generated by EF
    • Parameters: For performance and security EF tends to parameterize queries.  The values of each parameter are recorded so you can re-run the operation with the exact values used.
    • Transaction: When an operation is performed in a transaction context the transaction Id and isolation level are recorded.
    • Database Connection Information: The server name, server version, command timeout, and provider used to access the database.
    • Call Stack: (Optional) The full call stack for the current thread down to the EF operation so you can determine exactly what LINQ action or method caused the database operation to be executed.

    The following is an example of an insert run by Entity Framework as part of saving changes:

    Entity Framework Save Changes Log Message

    Entity Framework Save Changes Log Message

           

    In this example you can see the full query, parameter values, information on the transaction (so on a busy system you can see what statements were really part of the same transaction, even if there are multiple operations on the same thread concurrently) as well as the server and call stack that caused the action.  Recording the call stack can be disabled in configuration but it’s particularly useful when attempting to figure out the source of excessive database calls due to lazy loading or a lack of caching.

    Source Code for related Entity Framework Action

    Source Code for related Entity Framework Action

           

    The agent works to attribute each database operation to the part of the source code that triggered the operation.  In the case of the example above (taken from the unit tests for the Agent) it correctly attributed it to the save changes call in the unit test.  If the source code is available on your computer the exact line is displayed in the source code viewer.

     

    See Also