Search code examples
asp.net-coreodata

How can I view the OData sql generated from [EnableQuery]


Using: Visual Studio Code, ASP.NET Core 3.1, Microsoft.AspNetCore.OData 7.4.0-beta

I am new to OData and would like a way to examine the SQL statement generated from the [EnableQuery] action. I don't have a database profiler and can't readily see options on how to log or intercept the SQL. I want this to ensure that OData queries like /api/people(30)?$select=name, title are just selecting the name and title columns instead of all the columns when it executes. As things become more complicated, it seems easy for me to unintentionally materialize the query prematurely. Or in any event i just want to see the SQL. I like how Entity Framework Core can hook into the ASP.NET logging. Can't find such a thing for OData. Thanks.


Solution

  • A good approach is to assign the Logger to DbContextOptions during the initialization. The following example will output the SQL generated code to the console.

    public void ConfigureServices(IServiceCollection services)
    {
        ILoggerFactory dbLoggerFactory = LoggerFactory.Create(builder => { builder.AddConsole(); });
    
        services.AddDbContext<ApplicationDbContext>(
            options =>
            {
                options.UseSqlite(Configuration.GetConnectionString("DefaultConnection"))
                    .UseLoggerFactory(dbLoggerFactory);
            }
        );
    
        //... other services configuration...
    }
    

    Then the query persons?$select=id,name will output something similar to:

    enter image description here