EF Core 5.0: Using ToQueryString() method to translate LINQ query to SQL

Entity Framework Core 5.0 comes with SQL-based brother to ToString() method for LINQ-queries. This method is called ToQueryString() and it returns provider-specific SQL without connecting to database server. In some means it’s similar to ToTraceString() method of Entity Framework. This blog post shows how ToQueryString() method works.

NB! At the time of writing this post .NET Core 5.0 and EF Core 5.0 are both in Preview and things may change in future versions of EF Core 5.0.

I created new ASP.NET Core web application project with latest Visual Studio 2019 Preview and connected EF Core to one of my existing databases. I added just few entities and primitive DbContext to try out how ToQueryString() extension method works.

public class Customer
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}

public class Project
{
    public Guid Id { get; set; }
    public string Title { get; set; }
    public string ProjectKey { get; set; }

    public Customer Customer { get; set; }
}

public class MyDbContext : DbContext
{
    public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
    {
    }

    public DbSet<Customer> Customers { get; set; }
    public DbSet<Project> Projects { get; set; }
}

I injected my DbContext to HomeController and in Index() action I wrote a query to see what ToQueryString() method returns. I was a bit clever when writing the query – notice how I used variable called prefix in LINQ expression.

public class HomeController : Controller
{
    private readonly MyDbContext _dataContext;

    public HomeController(MyDbContext dataContext)
    {
        _dataContext = dataContext;
    }

    public IActionResult Index()
    {
        var prefix = "A";
        var query = _dataContext.Projects
                                .Include(p => p.Customer)
                                .Where(p => p.Customer.Name.StartsWith(prefix))
                                .OrderBy(p => p.Customer.Name)
                                .ThenBy(p => p.Title)
                                .Select(p => new { Project = p.Title, Customer = p.Customer.Name });

        var queryString = query.ToQueryString();
        var result = query.FirstOrDefault();
        return View();
    }
}

When running the code in debug mode and checking the value of queryString variable we can see nice formatted SQL in Text Visualizer window.

EF Core query as a string in Visual Studio Text Visualizer

The best thing is – we can take this SQL with copy and paste to SQL Server Management Studio (SSMS) or some other database tool to investigate the query closer. It’s ready to run without any modifications.

When ToQueryString() doesn’t work

There’s a little gotcha with ToQueryString() method – we cannot use it with methods that immediately run SQL query. It gives us valid query for ToList() and ToListAsync() methods but if we call FirstOrDefault() or FirstOrDefaultAsync() method on query then these methods add some more SQL that we cannot see with ToQueryString() method.

Let’s see what SQL is generated when we apply FirstOrDefault() method to query above. The actual query that is sent to database server is here.

SELECT TOP(1) [p].[Title] AS [Project], [c].[Name] AS [Customer]
FROM [Projects] AS [p]
LEFT JOIN [Customers] AS [c] ON [p].[CustomerId] = [c].[Id]
WHERE (@__prefix_0 = N'') OR ([c].[Name] IS NOT NULL AND (LEFT
([c].[Name], LEN(@__prefix_0)) = @__prefix_0))
ORDER BY [c].[Name], [p].[Title]

It’s almost the same but there’s TOP(1) after SELECT. The query gets even more different when we apply Count() method instead of FirstOrDefault().

SELECT COUNT(*)
FROM [Projects] AS [p]
LEFT JOIN [Customers] AS [c] ON [p].[CustomerId] = [c].[Id]
WHERE (@__prefix_0 = N'') OR ([c].[Name] IS NOT NULL AND (LEFT
([c].[Name], LEN(@__prefix_0)) = @__prefix_0))

For methods like FirstOrDefault() and Count() we need EF Core query logging. I will cover it in some of my future posts.

Wrapping up

ToQueryString() method helps us to see database queries generated by EF Core. It’s new feature in coming EF Core 5.0. We can use this method to get main part of SQL based on LINQ query we wrote. We cannot use ToQueryString() method to find out how query is modified by methods that send query to database – FirstOrDefault(), Count(), etc. For these methods we have to use EF Core logging that is not covered here. ToQueryString() method gives us SQL without making actual request to database server. The SQL we get is ready to run in database management tools for further investigation of generated query.

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    20 thoughts on “EF Core 5.0: Using ToQueryString() method to translate LINQ query to SQL

    • Pingback:Dew Drop – March 20, 2020 (#3158) | Morning Dew

    • Pingback:The Morning Brew - Chris Alcock » The Morning Brew #2958

    • Pingback:Read it #18 – letys.pl

    • March 12, 2021 at 12:13 am
      Permalink

      excellent, it was what I needed, thank you.

    • April 11, 2025 at 3:04 am
      Permalink

      Here, you can access a wide selection of casino slots from famous studios.
      Players can enjoy traditional machines as well as new-generation slots with vivid animation and bonus rounds.
      If you’re just starting out or an experienced player, there’s always a slot to match your mood.
      casino
      Each title are instantly accessible anytime and optimized for laptops and tablets alike.
      You don’t need to install anything, so you can jump into the action right away.
      The interface is user-friendly, making it convenient to browse the collection.
      Register now, and dive into the world of online slots!

    • April 14, 2025 at 5:07 am
      Permalink

      Supplier Sinar Baja Medan – Supplier BESI WELDED BEAM Terlengkap di medan, Distributor PLAT LUBANG Terbaik di medan, Supplier PLAT HAIR
      LINE Terlengkap dikota medan , Harga
      PLAT RAIL Termurah di medan – Sinar Baja

    • April 21, 2025 at 9:30 am
      Permalink

      Supplier Sinar Baja Medan – Distributor BESI COIL Termurah
      di medan, Toko BESI UNP / CNP Terlengkap di medan, Distributor PLAT BESI Termurah dikota medan , Harga BESI SIKU Termurah di medan – Sinar Baja

    • April 22, 2025 at 11:22 am
      Permalink

      Supplier Sinar Baja Medan – Agen PLAT KUNINGAN Terlengkap di medan, Supplier
      BESI EXPANDED Terbaik dikota medan, Distributor PLAT LUBANG
      Terbaik di medan , Toko PLAT BESI Terlengkap dikota medan – Sinar Baja

    • April 23, 2025 at 2:18 am
      Permalink

      This post is really a nice one it helps new web viewers, who are wishing for blogging.

    • April 25, 2025 at 9:00 pm
      Permalink

      Supplier Sinar Baja Medan – Harga PLAT RAIL Terbaik di medan,
      Supplier BESI UNP / CNP Termurah di medan,
      Toko BESI BAJA Terbaik di medan , Agen BESI H BEAM Terbaik dikota medan – Sinar Baja

    • April 28, 2025 at 12:43 pm
      Permalink

      Supplier Sinar Baja Medan – Harga PLAT BESI Terlengkap di
      medan, Supplier BESI COIL Terbaik dikota medan, Supplier
      BESI WF Termurah di medan , Supplier BESI SIKU
      Terpercaya dikota medan – Sinar Baja

    • July 6, 2025 at 2:24 pm
      Permalink

      My brother recommended I might like this blog. He was entirely
      right. This post truly made my day. You cann’t imagine simply how much time I had spent
      for this info! Thanks!

    • July 19, 2025 at 12:42 pm
      Permalink

      Contar com bônus na hora de fazer as apostas pode ser fundamental para aumentar suas chances de lucro, jogar jogos de slot grátis com bônus é uma ótima maneira de experimentar diferentes jogos de slot sem ter que gastar dinheiro. Outro jogo da NetEnt que é famoso por seus jackpots é o Arabian Nights, os entusiastas de jogos de mesa têm acesso aos jogos de blackjack. Ao mesmo tempo, verifique se o cassino online tem uma política clara de privacidade e segurança. Sim, você pode jogar Big Bass Splash no celular. O jogo é compatível com dispositivos móveis, permitindo que você o acesse diretamente pelo navegador ou através de aplicativos de cassinos online, sem perder qualidade de jogo. Age of The Gods 3 é um dos jogos slots de 10 centavos mais personalizáveis da lista. Você pode fazer muitas mudanças, sendo a principal delas o número de linhas de pagamento.
      https://rifaa.bayoussefmedia.com/sweet-bonanza-uma-analise-completa-do-jogo-de-caca-niquel-da-pragmatic-play-para-jogadores-brasileiros/
      @ 2024 Danpris Construtora – Todos Direitos Reservados. O Big Bass Splash é uma slot com cinco tambores e três linhas, com 10 linhas de pagamento. Nós também avaliamos se oferta pode ser utilizada nos melhores jogos de cassino e nos detalhes de cada um desses títulos, passando por tipo de jogo (slot, crash game, mesas), RTP, volatilidade, aposta mínima, recursos disponíveis, prêmio máximo por rodada e mais. No geral, a trilha sonora e a animação do Big Bass Splash criam uma atmosfera alegre de férias de pesca. Epic Slots released every week. Parte da família de jogos da Fat Panda Pragmatic Play, as mesmas do Tigre Sortudo slot, o Tigre Sortudo é super simples e divertido, com grade 5×3 e 10 linhas de pagamento. No geral, a trilha sonora e a animação do Big Bass Splash criam uma atmosfera alegre de férias de pesca.

    • July 22, 2025 at 12:10 pm
      Permalink

      Acompanhe o resumo das 10 melhores plataformas com rodadas grátis e, em seguida, a análise detalhada de cada plataforma: Conseguir ganhos substituindo o que o símbolo wild é um valor aleatório entre as principais armadilhas financeiras está cheio de credibilidade. Quanto eu escrevendo sobre apostagahna? Caso seja, nunca saber mais uma máquina de uma lagoa com dúvidas sobre esse é muito mais uma placa 5×3 padrão de apostagahna. Este título de minutos pagantes. Portanto, em uma ótima maneira de cassino big bass splash é muito simples e, giros grátis. Pesquisadores têm explorado o scatter. Outros. Informamos que a tabela horária para o dia 18 04 2025 (sexta-feira) e 21 04 2025 (segunda-feira) será com horários de DOMINGO. Nós também avaliamos se oferta pode ser utilizada nos melhores jogos de cassino e nos detalhes de cada um desses títulos, passando por tipo de jogo (slot, crash game, mesas), RTP, volatilidade, aposta mínima, recursos disponíveis, prêmio máximo por rodada e mais.
      https://raummed.com/spaceman-slot-by-pragmatic-play-a-stellar-review-for-uk-mobile-players/
      Cada tipo de poker possui suas regras e os jogadores podem aproveitar da versão demo na maioria deles para entender melhor o jogo antes de jogar por dinheiro real. E se são jogos da Pragmatic Play que chamam a sua atenção, nós oferecemos muitos deles aqui na KTO. Jogue Sugar Rush, que é da Pragmatic Play, assim como Big Bass Bonanza. Programa fidelidade Então vamos direto ao ponto: Pragmatic Play é uma máquina de fazer slot com esteroides, empilhando títulos insanos atrás de títulos mais insanos ainda — e tudo isso você pode testar aqui mesmo no demoslotsfun, sem pagar nada, sem se cadastrar, e com zero paciência pra burocracia. Jogue Big Bass Bonanza, o jogo do pescador, no cassino da KTO e ganhe até 2.100x o valor da sua aposta! Não é atoa que a série Big Bass se tornou um verdadeiro estandarte da cultura iGaming. Big Bass Bonanza, o jogo originário da série, é um jogo do pescador com bons gráficos, rodadas grátis empolgantes com a funcionalidade de multiplicadores e de jogabilidade simples.

    • July 24, 2025 at 1:04 am
      Permalink

      Excellent post. Keep posting such kind of info on your page.

      Im really impressed by it.
      Hi there, You’ve performed a great job. I’ll certainly digg it and in my
      opinion suggest to my friends. I’m confident they will be
      benefited from this web site.

      My site :: Packaging Machine

    Leave a Reply

    Your email address will not be published. Required fields are marked *