Performance de código Entity Framework Core - Parte 1

Published May 23 2022 09:36 AM 646 Views
Microsoft

Uma abordagem objetiva

 

Por onde começar?

Quem ainda não passou por isso um dia é porque ainda é muito novo nessa vida de desenvolvedor de software.

Aquele projeto que vem se arrastando há meses chega finalmente ao grande momento de ir para a produção, quebra-se a garrafa de champanhe no casco, liberam-se as amarras e em poucos minutos fica evidente que o nosso transatlântico não se move na velocidade desejada.

 

O próximo capítulo dessa história passa pelo inevitável apontar de dedos, afinal precisamos arrumar um culpado e esse negócio de análise objetiva dos fatos e definição de ações pode muito bem ficar para depois.

 

Pra encurtar a história o nosso navio cruzará os mares com o auxílio de um rebocador, alguns remadores e talvez um velame que tem que ser recolhido com vento forte pois a estrutura não aguenta os novos mastros.

 

Um conjunto de fatores leva a um baixo desempenho do software, arquitetura ruim, pouca experiência das pessoas, requisitos mal definidos, uso das ferramentas e práticas menos adequadas às necessidades, entre outros.

 

Não é o código

Não mesmo? É parte do meu trabalho analisar aplicações em produção e encontrar gargalos de performance. Muitas vezes eu me deparo com consultas ao banco de dados que não tem bom tempo de resposta ou infraestrutura de rede com restrições de banda.

 

"Ha ha, tá vendo? A culpa é do ambiente". Escuto isso com frequência, alguém se refere ao ambiente como sendo algum tipo de entidade de cujo humor dependem todos os problemas do software o que, sob o ponto de vista de uma análise objetiva, é tão preciso quanto dizer que um leprechaun está bagunçando os servidores.

 

Na grande maioria das vezes, os problemas de desempenho estão ligados diretamente à decisões feitas na hora de escrever o código. A consulta pouco eficiente é parte da aplicação ela é parte do código, se existe um requisito de limitação de banda de rede o tráfego tem que ser otimizado, comunicação tem custos, uso de memória tem custos, processamento tem custos e assim segue.

 

Na maior parte das vezes os problemas de desempenho que eu encontro estão ligados diretamente ao código.

 

E como desenvolvedor o que eu faço?

Se você escolheu ganhar a vida desenvolvendo software a primeira coisa que tem que ficar bem clara, se ainda não está, é que esta é uma carreira de aprendizado contínuo.

 

É fundamental entender como as coisas funcionam, eu não programo mais em nenhuma das linguagens com as quais eu comecei, mas os conceitos que aprendi eu uso até hoje. Linguagens e ferramentas surgem e desaparecem (ou viram legados), fundamentos se mantém.

 

No ferramental moderno de desenvolvimento ninguém programa usando somente a linguagem de programação. Stacks de desenvolvimento são compostos não apenas por compiladores, mas também por bibliotecas e outros componentes que simplificam o trabalho de escrever código. O desenvolvedor de software comercial trabalha quase sempre em um nível alto de abstração, ou seja, tudo que eu escrevo utiliza código que eu não escrevi.

 

É fundamental entender o que fazem as bibliotecas utilizadas. O que está por baixo do capô? Como funciona? Tem que saber o que acontece. Com o código fonte cada vez mais aberto fica mais fácil explorar o que está por trás de cada componente.

 

O código é executado em um sistema operacional, tem que entender pelo menos o básico do sistema operacional, a aplicação se comunica com outros serviços através da infraestrutura de rede, tem que entender alguma coisa de rede e protocolos, se acessa o banco de dados relacional precisa conhecer SQL, e assim vai. Não dá pra achar que basta saber uma linguagem de programação.

 

Em algum momento você atinge algum limite que é físico, o computador é um equipamento eletrônico que possui um numero limitado de ciclos de CPU ou uma quantidade limitada de bytes de memória que podem ser endereçados. O código não dispõe de recursos infinitos, mesmo na nuvem. Mais recursos nem sempre resolvem problemas de software mal escrito.

 

É muito comum encontrar cenários que podem ser resolvidos de maneiras diferentes, por isso um bom entendimento de algoritmos e estruturas de dados se faz necessário. Boa parte da otimização de código vem não dos passos executados, mas daqueles que são eliminados. Eu vejo muita gente preocupada com arquiteturas sofisticadas, design patterns e afins, mas que pulou por completo a parte dos conceitos.

 

Eu tenho que ser um cientista pra programar bem?

Não. Pelo contrário, as ferramentas atuais são feitas para que possamos trabalhar em nível mais alto, porém é muito importante entendê-las para utilizá-las da forma mais eficiente possível e saber escolher a ferramenta certa para cada trabalho.

 

"Pra quem tem martelo tudo é prego." (dito popular)

Otimização prematura em geral é ruim, em alguns cenários a otimização de código pode ter impactos negativos na legibilidade com um ganho pequeno em termos de eficiência. Evitar ineficiências conhecidas traz de imediato um impacto bastante positivo na busca por código melhor.

 

Próximos passos

A minha ideia é escrever artigos que ajudem a produzir código com melhor desempenho em C# e .NET que hoje são a minha especialidade, no futuro outras coisas poderão ser a minha especialidade. Também quero abordar ferramentas e técnicas que podem ser usadas para identificar e melhorar o desempenho de aplicações.

 

Pretendo começar com alguns tópicos sobre ORM usando o Entity Framework Core pois este é um assunto que é bastante comum no contexto de aplicações e que eu vejo as pessoas tropeçando com alguma frequência.

 

Nessa proposta pretendo ser sempre o mais objetivo e direto possível, tentando sempre usar o nível de detalhe necessário para ilustrar o meu ponto de vista.

 

Uma coisa que pra mim sempre foi muito clara é que eu não sei tudo, na verdade a quantidade de coisas que eu não sei é por certo muito maior do que as que eu sei. Não sou em momento algum dono da verdade e sempre posso estar sujeito a erros. As discussões civilizadas serão sempre bem-vindas.

 

Melhore as consultas com Entity Framework Core

 

Os problemas com o mapeamento objeto-relacional

Frameworks de mapeamento objeto-relacional (Object Relational Mapping – ORM) são ferramentas excelentes no trabalho de trazer os dados do modelo dos servidores de dados relacionais, como Sql Server, para o modelo orientado a objetos das linguagens de programação.

Por outro lado, esses frameworks criam uma impressão equivocada de que o programador não precisa mais entender o modelo relacional e sequer se preocupar em como escrever consultas da melhor forma até que os usuários comecem a reclamar da velocidade.

 

O comum nesses momentos é culpar o framework, dizer que é lento mesmo e que talvez na próxima versão o desempenho seja melhor, porém o mau uso responde essa questão mais vezes do que o contrário.

 

Assuma o controle

O desenvolvedor tem que entender SQL. Não dá para fugir, no final os dados são manipulados pelo SGBD (Sistema Gerenciador de Banco de Dados) e a interface padrão para esses sistemas é a linguagem SQL (Structured Query Language).

 

O que bibliotecas de ORM fazem é gerar as instruções da linguagem SQL de forma dinâmica a partir do código. Entity Framework (EF) e Entity Framework Core (EF Core), constroem as consultas SQL a partir do código na forma de instruções LINQ (Language Integrated Query) ou métodos de extensão.

 

Para assumir o controle é necessário ver as queries que são geradas e melhorá-las quando necessário ou identificar possíveis melhorias no esquema de banco de dados como índices ou modelagem mais eficiente. A ideia aqui é focar no EF Core 6.0, mas entender e otimizar consultas é um passo importante quando se investiga o desempenho de aplicações quaisquer que sejam.

 

Uma forma de visualizar as consultas em tempo de desenvolvimento é configurar o log no DbContext:

 

// Exemplo de configuração de log no DbContext usando uma aplicação console

using var loggerFactory = LoggerFactory.Create(builder => {
    builder.AddConsole().AddFilter("",LogLevel.Information);
});

var options = new DbContextOptionsBuilder<AdvWorksDbContext>()
    .UseLoggerFactory(loggerFactory)
    .UseSqlServer("Data Source=(localdb)\\MSSQLLocalDB;Database=AdventureWorksLT2016;Integrated Security=true")
    .Options;

using var context = new AdvWorksDbContext(options);

A classe DbContext pode ser configurada através de uma instância de DbContextOptions e nessa configuração pode ser passado um LoggerFactory que será usado em tempo de execução para obter uma instância de ILogger. Quando o nível de informação é configurado para LogLevel.Information, cada comando será registrado com o respectivo tempo de execução como no exemplo abaixo:

 

var qry = context.Customers;

foreach (var item in qry) {
   ...
}
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (25ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT [c].[CustomerID], [c].[CompanyName], [c].[EmailAddress], [c].[FirstName], [c].[LastName], [c].[MiddleName], [c].[ModifiedDate], [c].[NameStyle], [c].[PasswordHash], [c].[PasswordSalt], [c].[Phone], [c].[rowguid], [c].[SalesPerson], [c].[Suffix], [c].[Title]
      FROM [SalesLT].[Customer] AS [c]

Uma alternativa mais simples ao Microsoft.Extensions.Logging é o uso de Simple Logging, uma funcionalidade introduzida no EF Core 5.0 e que permite de forma simples associar uma ação (Action<T>) que aceita uma string. O exemplo abaixo configura o DbContext para direcionar os logs para a console usando o método LogTo:

 

var options = new DbContextOptionsBuilder<AdvWorksDbContext>()
    .LogTo(Console.WriteLine, LogLevel.Information)
    .UseSqlServer("Data Source=(localdb)\\MSSQLLocalDB;Database=AdventureWorksLT2016;Integrated Security=true")
    .Options;

Quando se usa injeção de dependências o Microsoft.Extensions.Log é configurado implicitamente:

 

        services.AddDbContext<AdvWorksDbContext>(options => { options
            .UseSqlServer("Configuration["ConnectionStrings:Default]");
        });

No arquivo appsettings.json é possível configurar o nível de log desejado para o EF Core:

 

{
  "Logging": {
    "LogLevel": {
      "Microsoft.EntityFrameworkCore": "Information"
    }
  },
  ...

Uma funcionalidade bastante útil para correlacionar as consultas nos logs com os comandos do código é o uso da função TagWith que possibilita adicionar um comentário em cada comando:

 

    var qry = context.Customers.TagWith("Traz todos os clientes").
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (22ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      -- Traz todos os clientes

      SELECT [c].[CustomerID], [c].[CompanyName], [c].[EmailAddress], [c].[FirstName], [c].[LastName], [c].[MiddleName], [c].[ModifiedDate], [c].[NameStyle], [c].[PasswordHash], [c].[PasswordSalt], [c].[Phone], [c].[rowguid], [c].[SalesPerson], [c].[Suffix], [c].[Title]
      FROM [SalesLT].[Customer] AS [c]

Consultas com alto tempo de execução são as que devem ser investigadas de forma mais profunda. Se necessário peça ajuda a um especialista de banco de dados sobre como identificar as consultas mais pesadas e ações para melhorar o desempenho.

 

Sempre olhe as consultas geradas!

Trazendo só o necessário

A regra mais básica a ser respeitada na hora de escrever uma consulta a qualquer fonte de dados é traga somente os dados que for utilizar. Não escreva consultas sem uma cláusula WHERE e nunca escreva consultas usando SELECT *, lembre-se que os dados tem de ser transportados através da rede e mapeados para propriedades de classe em código e isso toma tempo e consome recursos desnecessários. Menos é mais.

 

var qry = context.Customers;

foreach (var item in qry) {
   ...
}

Partindo dessa premissa, qual o problema com a consulta do exemplo acima?

 

Se não colocarmos sob um contexto não há nenhum problema. Então vamos estipular um requisito: preciso obter uma lista com Id, nome e sobrenome de todos os clientes.

 

Nesse caso o erro fica mais evidente, a consulta traz todos os dados de todos os clientes. Se a empresa tem muitos clientes (situação bastante desejável) podemos ter tempos longos para trazer e mapear todos os dados.

 

Ao definir o modelo de objetos para as entidades de negócio, criamos classes que realmente mapeiam as informações do domínio de negócios para o código. Isso é perfeito quando visualizamos detalhes de uma entidade (um cliente por exemplo) ou atualizamos as informações no banco de dados, porém isso não é o ideal quando se necessita apenas de alguns dados.

 

Não é necessário usar todas as propriedades de uma classe ao efetuar uma consulta, LINQ oferece a possibilidade de utilizar projeções que é o equivalente direto para um select com lista de campos.

 

O exemplo abaixo utiliza o método Select com um tipo anônimo que contém apenas os dados desejados:

 

var qry = context.Customers.TagWith("Traz apenas Id, nome e sobrenome dos clientes")
    .Select(c => new {
         CustomerId = c.CustomerId,
         FirstName = c.FirstName,
         LastName = c.LastName
     });

Implicitamente o compilador definirá uma classe que representa o tipo anônimo. Veja a diferença da consulta gerada no log:

 

info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (24ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      -- Traz apenas Id, nome e sobrenome dos clientes

      SELECT [c].[CustomerID] AS [CustomerId], [c].[FirstName], [c].[LastName]
      FROM [SalesLT].[Customer] AS [c]

Tipos anônimos são bons quando utilizados dentro de um mesmo método, porém não são opção quando se deseja passar informações para outros métodos, seja como parâmetro ou como retorno.

 

Para esses cenários podem ser definidas classes específicas com apenas os dados que se deseja obter. Ex.:

 

    ...
    internal class MinimalCustomer
    {
        public int CustomerId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    ...
    var qry = context.Customers
        .Select(c => new MinimalCustomer{
            CustomerId = c.CustomerId,
            FirstName = c.FirstName,
            LastName = c.LastName
        });
    ...

Projeções resolvem a questão de trazer apenas as colunas necessárias, trazer apenas as linhas necessárias é função do Where. Sempre que possível gere consultas com critérios de filtro, lembre-se que a base de dados pode crescer ao longo do tempo.

 

Por exemplo, podemos trazer apenas os dados de clientes que sejam atendidos pelo vendedor que está usando a aplicação no momento.

 

  var currentUser = "adventure-works\\david8";
  var qry = context.Customers
      .Where(c=>c.SalesPerson== currentUser)
      .Select(c => new {
          CustomerId = c.CustomerId,
          FirstName = c.FirstName,
          LastName = c.LastName
      });

O método Where acrescenta a cláusula WHERE na consulta SQL e utiliza parâmetros para dificultar a injeção de SQL: 

 

info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (30ms) [Parameters=[@__currentUser_0='?' (Size = 256)], CommandType='Text', CommandTimeout='30']
      SELECT [c].[CustomerID] AS [CustomerId], [c].[FirstName], [c].[LastName]
      FROM [SalesLT].[Customer] AS [c]
      WHERE [c].[SalesPerson] = @__currentUser_0

Se não for possível forçar o uso de filtros de consulta na aplicação é possível limitar o número de resultados retornados. Na maioria das vezes não faz nenhum sentido retornar milhares ou milhões de linhas. O método Take pode ser usado para colocar um limitador:

 

  var qry = context.Customers
      .Where(c=>c.SalesPerson== currentUser)
      .Select(c => new {
          CustomerId = c.CustomerId,
          FirstName = c.FirstName,
          LastName = c.LastName
      })
      .OrderBy(c=>c.LastName)
      .Take(100);
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (26ms) [Parameters=[@__p_1='?' (DbType = Int32), @__currentUser_0='?' (Size = 256)], CommandType='Text', CommandTimeout='30']
      SELECT TOP(@__p_1) [c].[CustomerID] AS [CustomerId], [c].[FirstName], [c].[LastName]
      FROM [SalesLT].[Customer] AS [c]
      WHERE [c].[SalesPerson] = @__currentUser_0
      ORDER BY [c].[LastName]

Note no exemplo anterior o método Take insere a cláusula TOP no comando SQL. O uso de OrderBy é para garantir a ordem dos resultados. Se omitido teremos alertas no log indicando que não há garantia de ordem nos resultados de comandos SQL sem especificar ORDER BY:

 

warn: Microsoft.EntityFrameworkCore.Query[10102]
      The query uses a row limiting operator ('Skip'/'Take') without an 'OrderBy' operator. This may lead to unpredictable results. If the 'Distinct' operator is used after 'OrderBy', then make sure to use the 'OrderBy' operator after 'Distinct' as the ordering would otherwise get erased.

 

Finalizando

Frameworks existem para facilitar o trabalho, mas é responsabilidade do programador entender o que eles fazem e utilizá-los da melhor forma. Esteja no controle.

 

Traga sempre apenas os dados necessários, mesmo que isso signifique escrever um pouco mais de código.

 

Aprenda SQL, é lenda urbana essa história de que o ORM nos livra de saber SQL.

 

Teste com massas de dados que reproduzam os cenários esperados em produção ou se possível que excedam esses cenários.

 

No caso do EF Core ou qualquer outro framework ORM, é necessário analisar as consultas geradas. Pelo menos as mais críticas.

 

Existem outras ferramentas que podem ser usadas para entender e otimizar comandos SQL, recomendo instalar o Azure Data Studio que permite conectar a bases de dados, executar comandos, investigar planos de acesso entre diversas funções. É possível ampliar a funcionalidade da ferramenta através de extensões e uma que eu recomendo para entender o que acontece por trás do ORM é a SQL Server Profiler.

 

Referências

%3CLINGO-SUB%20id%3D%22lingo-sub-3408195%22%20slang%3D%22pt-BR%22%3ECode%20Performance%20Entity%20Framework%20Core%20-%20Part%201%3C%2FLINGO-SUB%3E%3CLINGO-BODY%20id%3D%22lingo-body-3408195%22%20slang%3D%22pt-BR%22%3E%3CH2%20dir%3D%22auto%22%20id%3D%22toc-hId-444668004%22%20id%3D%22toc-hId-445532753%22%3EAn%20objective%20approach%3C%2FH2%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CH3%20dir%3D%22auto%22%20id%3D%22toc-hId-1135229478%22%20id%3D%22toc-hId-1136094227%22%3E%3CA%20id%3D%22user-content-por-onde-come%C3%A7ar%22%20class%3D%22anchor%22%20href%3D%22https%3A%2F%2Fgithub.com%2FAppInnovationBrazil%2Fblog%2Fblob%2Fmain%2Fdrafts%2Fef-core-perf%2F01.Assuma%2520o%2520controle.md%23por-onde-come%25C3%25A7ar%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noreferrer%22%20aria-hidden%3D%22true%22%3E%3C%2FA%3EWhere%20to%20start%3F%3C%2FH3%3E%0A%3CP%3EWho%20hasn't%20been%20through%20this%20one%20day%20is%20because%20they're%20still%20very%20young%20in%20this%20software%20developer%20life.%3C%2FP%3E%0A%3CP%3EThat%20project%20that%20has%20been%20dragging%20on%20for%20months%20finally%20comes%20to%20the%20great%20moment%20of%20going%20to%20production%2C%20breaks%20the%20bottle%20of%20champagne%20in%20the%20hull%2C%20the%20moorings%20are%20released%20and%20in%20a%20few%20minutes%20it%20becomes%20evident%20that%20our%20ocean%20liner%20does%20not%20move%20at%20the%20desired%20speed.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EThe%20next%20chapter%20of%20this%20story%20goes%20through%20the%20inevitable%20finger%20pointing%2C%20after%20all%20we%20need%20to%20find%20a%20culprit%20and%20this%20business%20of%20objective%20analysis%20of%20facts%20and%20definition%20of%20actions%20may%20well%20stick%20for%20later.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3ETo%20shorten%20the%20story%20our%20ship%20will%20cross%20the%20seas%20with%20the%20help%20of%20a%20tugboat%2C%20some%20rowers%20and%20perhaps%20a%20canopy%20that%20has%20to%20be%20collected%20with%20strong%20wind%20because%20the%20structure%20can%20not%20stand%20the%20new%20masts.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EA%20set%20of%20factors%20leads%20to%20poor%20software%20performance%2C%20poor%20architecture%2C%20poor%20people%20experience%2C%20poorly%20defined%20requirements%2C%20tool%20usage%2C%20and%20practices%20less%20suited%20to%20needs%2C%20among%20others.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CH3%20dir%3D%22auto%22%20id%3D%22toc-hId--672224985%22%20id%3D%22toc-hId--671360236%22%3E%3CA%20id%3D%22user-content-n%C3%A3o-%C3%A9-o-c%C3%B3digo%22%20class%3D%22anchor%22%20href%3D%22https%3A%2F%2Fgithub.com%2FAppInnovationBrazil%2Fblog%2Fblob%2Fmain%2Fdrafts%2Fef-core-perf%2F01.Assuma%2520o%2520controle.md%23n%25C3%25A3o-%25C3%25A9-o-c%25C3%25B3digo%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noreferrer%22%20aria-hidden%3D%22true%22%3E%3C%2FA%3EIt's%20not%20the%20code%3C%2FH3%3E%0A%3CP%3EIsn't%20that%20right%3F%20It's%20part%20of%20my%20job%20to%20analyze%20production%20applications%20and%20find%20performance%20bottlenecks.%20I%20often%20come%20up%20with%20database%20queries%20that%20don't%20have%20good%20response%20time%20or%20network%20infrastructure%20with%20bandwidth%20restrictions.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3E%22Ha%20ha%2C%20see%3F%20It's%20the%20environment's%20fault.%22%20I%20hear%20this%20often%2C%20someone%20refers%20to%20the%20environment%20as%20being%20some%20kind%20of%20entity%20whose%20mood%20all%20the%20problems%20of%20the%20software%20depend%2C%20which%2C%20from%20the%20point%20of%20view%20of%20an%20objective%20analysis%2C%20is%20as%20accurate%20as%20saying%20that%20a%20leprechaun%20is%20messing%20up%20the%20servers.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EMost%20of%20the%20time%2C%20performance%20issues%20are%20directly%20linked%20to%20decisions%20made%20when%20writing%20code.%20The%20inefficient%20query%20is%20part%20of%20the%20application%20it%20is%20part%20of%20the%20code%2C%20if%20there%20is%20a%20requirement%20of%20network%20bandwidth%20throttling%20traffic%20has%20to%20be%20optimized%2C%20communication%20has%20costs%2C%20memory%20usage%20has%20costs%2C%20processing%20has%20costs%20and%20so%20follows.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EMost%20of%20the%20time%20the%20performance%20issues%20I%20encounter%20are%20directly%20linked%20to%20the%20code.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CH3%20dir%3D%22auto%22%20id%3D%22toc-hId-1815287848%22%20id%3D%22toc-hId-1816152597%22%3E%3CA%20id%3D%22user-content-e-como-desenvolvedor-o-que-eu-fa%C3%A7o%22%20class%3D%22anchor%22%20href%3D%22https%3A%2F%2Fgithub.com%2FAppInnovationBrazil%2Fblog%2Fblob%2Fmain%2Fdrafts%2Fef-core-perf%2F01.Assuma%2520o%2520controle.md%23e-como-desenvolvedor-o-que-eu-fa%25C3%25A7o%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noreferrer%22%20aria-hidden%3D%22true%22%3E%3C%2FA%3EAnd%20as%20a%20developer%20what%20do%20I%20do%3F%3C%2FH3%3E%0A%3CP%3EIf%20you%20chose%20to%20make%20a%20living%20developing%20software%20the%20first%20thing%20that%20has%20to%20be%20very%20clear%2C%20if%20not%20yet%2C%20is%20that%20this%20is%20a%20career%20of%20continuous%20learning.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EIt's%20critical%20to%20understand%20how%20things%20work%2C%20I%20don't%20program%20anymore%20in%20any%20of%20the%20languages%20I%20started%20with%2C%20but%20the%20concepts%20I've%20learned%20I%20use%20to%20this%20day.%20Languages%20and%20tools%20arise%20and%20disappear%20(or%20have%20become%20legacies)%2C%20fundamentals%20remain.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EIn%20the%20modern%20development%20tooling%20no%20one%20program%20using%20only%20the%20programming%20language.%20Development%20stacks%20are%20composed%20not%20only%20of%20compilers%2C%20but%20also%20by%20libraries%20and%20other%20components%20that%20simplify%20the%20work%20of%20writing%20code.%20The%20commercial%20software%20developer%20almost%20always%20works%20at%20a%20high%20level%20of%20abstraction%2C%20that%20is%2C%20everything%20I%20write%20uses%20code%20that%20I%20have%20not%20written.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EIt%20is%20essential%20to%20understand%20what%20the%20libraries%20used%20do.%20What's%20under%20the%20hood%3F%20How%20does%20it%20work%3F%20You%20have%20to%20know%20what%20happens.%20With%20source%20code%20increasingly%20open%2C%20it's%20easier%20to%20explore%20what's%20behind%20each%20component.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EThe%20code%20runs%20on%20an%20operating%20system%2C%20has%20to%20understand%20at%20least%20the%20basics%20of%20the%20operating%20system%2C%20the%20application%20communicates%20with%20other%20services%20through%20the%20network%20infrastructure%2C%20has%20to%20understand%20something%20network%20and%20protocols%2C%20if%20accesses%20the%20relational%20database%20needs%20to%20know%20SQL%2C%20and%20so%20it%20goes.%20You%20can't%20think%20it's%20enough%20to%20know%20a%20programming%20language.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EAt%20some%20point%20you%20reach%20some%20limit%20that%20is%20physical%2C%20the%20computer%20is%20an%20electronic%20equipment%20that%20has%20a%20limited%20number%20of%20CPU%20cycles%20or%20a%20limited%20amount%20of%20bytes%20of%20memory%20that%20can%20be%20addressed.%20The%20code%20does%20not%20have%20infinite%20resources%2C%20even%20in%20the%20cloud.%20More%20features%20don't%20always%20solve%20poorly%20written%20software%20issues.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EIt%20is%20very%20common%20to%20find%20scenarios%20that%20can%20be%20solved%20in%20different%20ways%2C%20so%20a%20good%20understanding%20of%20algorithms%20and%20data%20structures%20is%20necessary.%20Much%20of%20the%20code%20optimization%20comes%20not%20from%20the%20steps%20you%20take%2C%20but%20from%20those%20that%20are%20eliminated.%20I%20see%20a%20lot%20of%20people%20worried%20about%20sophisticated%20architectures%2C%20design%20patterns%20and%20the%20like%2C%20but%20that%20has%20completely%20skipped%20the%20concepts%20part.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CH3%20dir%3D%22auto%22%20id%3D%22toc-hId-7833385%22%20id%3D%22toc-hId-8698134%22%3E%3CA%20id%3D%22user-content-eu-tenho-que-ser-um-cientista-pra-programar-bem%22%20class%3D%22anchor%22%20href%3D%22https%3A%2F%2Fgithub.com%2FAppInnovationBrazil%2Fblog%2Fblob%2Fmain%2Fdrafts%2Fef-core-perf%2F01.Assuma%2520o%2520controle.md%23eu-tenho-que-ser-um-cientista-pra-programar-bem%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noreferrer%22%20aria-hidden%3D%22true%22%3E%3C%2FA%3EDo%20I%20have%20to%20be%20a%20scientist%20to%20program%20well%3F%3C%2FH3%3E%0A%3CP%3ENo.%20On%20the%20contrary%2C%20the%20current%20tools%20are%20made%20so%20that%20we%20can%20work%20at%20a%20higher%20level%2C%20but%20it%20is%20very%20important%20to%20understand%20them%20to%20use%20them%20as%20efficiently%20as%20possible%20and%20know%20how%20to%20choose%20the%20right%20tool%20for%20each%20job.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CBLOCKQUOTE%3E%0A%3CP%3E%3CSTRONG%3E%22For%20those%20with%20a%20hammer%2C%20everything%20is%20a%20nail.%22%3C%2FSTRONG%3E%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E(popular%20said)%3C%2FP%3E%0A%3C%2FBLOCKQUOTE%3E%0A%3CP%3EPremature%20optimization%20is%20generally%20poor%2C%20in%20some%20scenarios%20code%20optimization%20can%20have%20negative%20impacts%20on%20readability%20with%20a%20small%20gain%20in%20terms%20of%20efficiency.%20Avoiding%20known%20inefficiencies%20immediately%20has%20a%20very%20positive%20impact%20on%20the%20search%20for%20better%20code.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CH3%20dir%3D%22auto%22%20id%3D%22toc-hId--1799621078%22%20id%3D%22toc-hId--1798756329%22%3E%3CA%20id%3D%22user-content-pr%C3%B3ximos-passos%22%20class%3D%22anchor%22%20href%3D%22https%3A%2F%2Fgithub.com%2FAppInnovationBrazil%2Fblog%2Fblob%2Fmain%2Fdrafts%2Fef-core-perf%2F01.Assuma%2520o%2520controle.md%23pr%25C3%25B3ximos-passos%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noreferrer%22%20aria-hidden%3D%22true%22%3E%3C%2FA%3ENext%20steps%3C%2FH3%3E%0A%3CP%3EMy%20idea%20is%20to%20write%20articles%20that%20help%20produce%20code%20with%20better%20performance%20in%20C%23%20and%20.NET%20that%20today%20are%20my%20specialty%2C%20in%20the%20future%20other%20things%20may%20be%20my%20specialty.%20I%20also%20want%20to%20address%20tools%20and%20techniques%20that%20can%20be%20used%20to%20identify%20and%20improve%20application%20performance.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EI%20want%20to%20start%20with%20some%20topics%20about%20ORM%20using%20Entity%20Framework%20Core%20because%20this%20is%20a%20subject%20that%20is%20quite%20common%20in%20the%20context%20of%20applications%20and%20that%20I%20see%20people%20stumbling%20over%20with%20some%20frequency.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EIn%20this%20proposal%20I%20intend%20to%20always%20be%20as%20objective%20and%20direct%20as%20possible%2C%20always%20trying%20to%20use%20the%20level%20of%20detail%20necessary%20to%20illustrate%20my%20point%20of%20view.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EOne%20thing%20that%20has%20always%20been%20very%20clear%20to%20me%20is%20that%20I%20don't%20know%20everything%2C%20in%20fact%20the%20amount%20of%20things%20I%20don't%20know%20is%20certainly%20much%20higher%20than%20the%20ones%20I%20know.%20I'm%20not%20at%20any%20time%20an%20owner%20of%20the%20truth%2C%20and%20I%20can%20always%20be%20subject%20to%20error.%20Civilized%20discussions%20will%20always%20be%20welcome.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CH2%20dir%3D%22auto%22%20id%3D%22toc-hId--1810124182%22%20id%3D%22toc-hId--1809259433%22%3E%3CA%20id%3D%22user-content-melhore-as-consultas-com-entity-framework-core%22%20class%3D%22anchor%22%20href%3D%22https%3A%2F%2Fgithub.com%2FAppInnovationBrazil%2Fblog%2Fblob%2Fmain%2Fdrafts%2Fef-core-perf%2F01.Assuma%2520o%2520controle.md%23melhore-as-consultas-com-entity-framework-core%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noreferrer%22%20aria-hidden%3D%22true%22%3E%3C%2FA%3EImprove%20queries%20with%20Entity%20Framework%20Core%3C%2FH2%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CH3%20dir%3D%22auto%22%20id%3D%22toc-hId--1119562708%22%20id%3D%22toc-hId--1118697959%22%3E%3CA%20id%3D%22user-content-os-problemas-com-o-mapeamento-objeto-relacional%22%20class%3D%22anchor%22%20href%3D%22https%3A%2F%2Fgithub.com%2FAppInnovationBrazil%2Fblog%2Fblob%2Fmain%2Fdrafts%2Fef-core-perf%2F01.Assuma%2520o%2520controle.md%23os-problemas-com-o-mapeamento-objeto-relacional%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noreferrer%22%20aria-hidden%3D%22true%22%3E%3C%2FA%3EProblems%20with%20object-relational%20mapping%3C%2FH3%3E%0A%3CP%3EObject%20Relational%20Mapping%20(ORM)%20frameworks%20are%20excellent%20tools%20in%20the%20work%20of%20bringing%20data%20from%20the%20model%20of%20relational%20data%20servers%2C%20such%20as%20Sql%20Server%2C%20to%20the%20object-oriented%20model%20of%20programming%20languages.%3C%2FP%3E%0A%3CP%3EOn%20the%20other%20hand%2C%20these%20frameworks%20create%20a%20mistaken%20impression%20that%20the%20programmer%20no%20longer%20needs%20to%20understand%20the%20relational%20model%20and%20even%20worry%20about%20how%20to%20write%20queries%20in%20the%20best%20way%20until%20users%20start%20complaining%20about%20speed.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EThe%20common%20thing%20in%20these%20moments%20is%20to%20blame%20the%20framework%2C%20to%20say%20that%20it%20is%20slow%20even%20and%20that%20maybe%20in%20the%20next%20version%20the%20performance%20is%20better%2C%20but%20the%20misuse%20answers%20this%20question%20more%20times%20than%20the%20other%20way%20around.%3C%2FP%3E%0A%3CH3%20dir%3D%22auto%22%20id%3D%22toc-hId-1367950125%22%20id%3D%22toc-hId-1368814874%22%3E%26nbsp%3B%3C%2FH3%3E%0A%3CH3%20dir%3D%22auto%22%20id%3D%22toc-hId--439504338%22%20id%3D%22toc-hId--438639589%22%3E%3CA%20id%3D%22user-content-assuma-o-controle%22%20class%3D%22anchor%22%20href%3D%22https%3A%2F%2Fgithub.com%2FAppInnovationBrazil%2Fblog%2Fblob%2Fmain%2Fdrafts%2Fef-core-perf%2F01.Assuma%2520o%2520controle.md%23assuma-o-controle%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noreferrer%22%20aria-hidden%3D%22true%22%3E%3C%2FA%3ETake%20control%3C%2FH3%3E%0A%3CP%3EThe%20developer%20has%20to%20understand%20SQL.%20You%20can't%20get%20away%2C%20in%20the%20end%20the%20data%20is%20manipulated%20by%20the%20DbMS%20(Database%20Manager%20System)%20and%20the%20default%20interface%20for%20these%20systems%20is%20the%20Structured%20Query%20Language%20(SQL).%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EWhat%20ORM%20libraries%20do%20is%20generate%20sql%20language%20statements%20dynamically%20from%20code.%20Entity%20Framework%20(EF)%20and%20Entity%20Framework%20Core%20(EF%20Core)%20build%20SQL%20queries%20from%20code%20in%20the%20form%20of%20Language%20Integrated%20Query%20(LINQ)%20statements%20or%20extension%20methods.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3ETo%20take%20control%20it%20is%20necessary%20to%20see%20the%20queries%20that%20are%20generated%20and%20improve%20them%20when%20necessary%20or%20identify%20possible%20improvements%20in%20the%20database%20schema%20such%20as%20indexes%20or%20more%20efficient%20modeling.%20The%20idea%20here%20is%20to%20focus%20on%20EF%20Core%206.0%2C%20but%20understanding%20and%20optimizing%20queries%20is%20an%20important%20step%20when%20investigating%20the%20performance%20of%20any%20applications.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EOne%20way%20to%20view%20queries%20at%20development%20time%20is%20to%20configure%20the%20log%20in%20DbContext%3A%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CDIV%20class%3D%22highlight%20highlight-source-cs%20notranslate%20position-relative%20overflow-auto%22%3E%0A%3CPRE%3E%3CSPAN%20class%3D%22pl-c%22%3E%2F%2F%20Exemplo%20de%20configura%C3%A7%C3%A3o%20de%20log%20no%20DbContext%20usando%20uma%20aplica%C3%A7%C3%A3o%20console%3C%2FSPAN%3E%0A%0A%3CSPAN%20class%3D%22pl-k%22%3Eusing%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-en%22%3Evar%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-en%22%3EloggerFactory%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3E%3D%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-en%22%3ELoggerFactory%3C%2FSPAN%3E.%3CSPAN%20class%3D%22pl-en%22%3ECreate%3C%2FSPAN%3E(%3CSPAN%20class%3D%22pl-en%22%3Ebuilder%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3E%3D%3C%2FSPAN%3E%26gt%3B%20%7B%0A%20%20%20%20%3CSPAN%20class%3D%22pl-en%22%3Ebuilder%3C%2FSPAN%3E.%3CSPAN%20class%3D%22pl-en%22%3EAddConsole%3C%2FSPAN%3E().%3CSPAN%20class%3D%22pl-en%22%3EAddFilter%3C%2FSPAN%3E(%22%22%2C%3CSPAN%20class%3D%22pl-en%22%3ELogLevel%3C%2FSPAN%3E.%3CSPAN%20class%3D%22pl-en%22%3EInformation%3C%2FSPAN%3E)%3B%0A%7D)%3B%0A%0A%3CSPAN%20class%3D%22pl-k%22%3Evar%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-en%22%3Eoptions%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3E%3D%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3Enew%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-en%22%3EDbContextOptionsBuilder%3C%2FSPAN%3E%26lt%3B%3CSPAN%20class%3D%22pl-en%22%3EAdvWorksDbContext%3C%2FSPAN%3E%26gt%3B()%0A%20%20%20%20.%3CSPAN%20class%3D%22pl-en%22%3EUseLoggerFactory%3C%2FSPAN%3E(%3CSPAN%20class%3D%22pl-smi%22%3EloggerFactory%3C%2FSPAN%3E)%0A%20%20%20%20.%3CSPAN%20class%3D%22pl-en%22%3EUseSqlServer%3C%2FSPAN%3E(%3CSPAN%20class%3D%22pl-s%22%3E%3CSPAN%20class%3D%22pl-pds%22%3E%22%3C%2FSPAN%3EData%20Source%3D(localdb)%3CSPAN%20class%3D%22pl-cce%22%3E%5C%5C%3C%2FSPAN%3EMSSQLLocalDB%3BDatabase%3DAdventureWorksLT2016%3BIntegrated%20Security%3Dtrue%3CSPAN%20class%3D%22pl-pds%22%3E%22%3C%2FSPAN%3E%3C%2FSPAN%3E)%0A%20%20%20%20.%3CSPAN%20class%3D%22pl-smi%22%3EOptions%3C%2FSPAN%3E%3B%0A%0A%3CSPAN%20class%3D%22pl-k%22%3Eusing%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-en%22%3Evar%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-en%22%3Econtext%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3E%3D%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-en%22%3Enew%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-en%22%3EAdvWorksDbContext%3C%2FSPAN%3E(%3CSPAN%20class%3D%22pl-en%22%3Eoptions%3C%2FSPAN%3E)%3B%0A%3C%2FPRE%3E%0A%3C%2FDIV%3E%0A%3CP%3EThe%20DbContext%20class%20can%20be%20configured%20through%20a%20DbContextOptions%20instance%2C%20and%20in%20this%20configuration%20a%20LoggerFactory%20can%20be%20passed%20that%20will%20be%20used%20at%20runtime%20to%20obtain%20an%20ILogger%20instance.%20When%20the%20information%20level%20is%20set%20to%20LogLevel.Information%2C%20each%20command%20will%20be%20registered%20with%20its%20runtime%20as%20in%20the%20example%20below%3A%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CDIV%20class%3D%22highlight%20highlight-source-cs%20notranslate%20position-relative%20overflow-auto%22%3E%0A%3CPRE%3E%3CSPAN%20class%3D%22pl-k%22%3Evar%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-en%22%3Eqry%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3E%3D%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-smi%22%3Econtext%3C%2FSPAN%3E.%3CSPAN%20class%3D%22pl-smi%22%3ECustomers%3C%2FSPAN%3E%3B%0A%0A%3CSPAN%20class%3D%22pl-k%22%3Eforeach%3C%2FSPAN%3E%20(%3CSPAN%20class%3D%22pl-k%22%3Evar%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-en%22%3Eitem%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3Ein%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-smi%22%3Eqry%3C%2FSPAN%3E)%20%7B%0A%20%20%20...%0A%7D%3C%2FPRE%3E%0A%3C%2FDIV%3E%0A%3CDIV%20class%3D%22snippet-clipboard-content%20notranslate%20position-relative%20overflow-auto%22%3E%0A%3CPRE%20class%3D%22notranslate%22%20lang%3D%22text%22%3E%3CCODE%3Einfo%3A%20Microsoft.EntityFrameworkCore.Database.Command%5B20101%5D%0A%20%20%20%20%20%20Executed%20DbCommand%20(25ms)%20%5BParameters%3D%5B%5D%2C%20CommandType%3D'Text'%2C%20CommandTimeout%3D'30'%5D%0A%20%20%20%20%20%20SELECT%20%5Bc%5D.%5BCustomerID%5D%2C%20%5Bc%5D.%5BCompanyName%5D%2C%20%5Bc%5D.%5BEmailAddress%5D%2C%20%5Bc%5D.%5BFirstName%5D%2C%20%5Bc%5D.%5BLastName%5D%2C%20%5Bc%5D.%5BMiddleName%5D%2C%20%5Bc%5D.%5BModifiedDate%5D%2C%20%5Bc%5D.%5BNameStyle%5D%2C%20%5Bc%5D.%5BPasswordHash%5D%2C%20%5Bc%5D.%5BPasswordSalt%5D%2C%20%5Bc%5D.%5BPhone%5D%2C%20%5Bc%5D.%5Browguid%5D%2C%20%5Bc%5D.%5BSalesPerson%5D%2C%20%5Bc%5D.%5BSuffix%5D%2C%20%5Bc%5D.%5BTitle%5D%0A%20%20%20%20%20%20FROM%20%5BSalesLT%5D.%5BCustomer%5D%20AS%20%5Bc%5D%0A%3C%2FCODE%3E%3C%2FPRE%3E%0A%3C%2FDIV%3E%0A%3CP%3EA%20simpler%20alternative%20to%20Microsoft.Extensions.Logging%20is%20the%20use%20of%20Simple%20Logging%2C%20a%20feature%20introduced%20in%20EF%20Core%205.0%20and%20that%20allows%20you%20to%20simply%20associate%20an%20action%20(%3CCODE%3EAction%3CT%3E%3C%2FT%3E%3C%2FCODE%3E)%20that%20accepts%20a%20string.%20The%20example%20below%20configures%20dbcontext%20to%20direct%20logs%20to%20the%20console%20using%20the%20LogTo%20method%3A%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CDIV%20class%3D%22highlight%20highlight-source-cs%20notranslate%20position-relative%20overflow-auto%22%3E%0A%3CPRE%3E%3CSPAN%20class%3D%22pl-k%22%3Evar%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-en%22%3Eoptions%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3E%3D%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3Enew%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-en%22%3EDbContextOptionsBuilder%3C%2FSPAN%3E%26lt%3B%3CSPAN%20class%3D%22pl-en%22%3EAdvWorksDbContext%3C%2FSPAN%3E%26gt%3B()%0A%20%20%20%20.%3CSPAN%20class%3D%22pl-en%22%3ELogTo%3C%2FSPAN%3E(%3CSPAN%20class%3D%22pl-smi%22%3EConsole%3C%2FSPAN%3E.%3CSPAN%20class%3D%22pl-smi%22%3EWriteLine%3C%2FSPAN%3E%2C%20%3CSPAN%20class%3D%22pl-smi%22%3ELogLevel%3C%2FSPAN%3E.%3CSPAN%20class%3D%22pl-smi%22%3EInformation%3C%2FSPAN%3E)%0A%20%20%20%20.%3CSPAN%20class%3D%22pl-en%22%3EUseSqlServer%3C%2FSPAN%3E(%3CSPAN%20class%3D%22pl-s%22%3E%3CSPAN%20class%3D%22pl-pds%22%3E%22%3C%2FSPAN%3EData%20Source%3D(localdb)%3CSPAN%20class%3D%22pl-cce%22%3E%5C%5C%3C%2FSPAN%3EMSSQLLocalDB%3BDatabase%3DAdventureWorksLT2016%3BIntegrated%20Security%3Dtrue%3CSPAN%20class%3D%22pl-pds%22%3E%22%3C%2FSPAN%3E%3C%2FSPAN%3E)%0A%20%20%20%20.%3CSPAN%20class%3D%22pl-smi%22%3EOptions%3C%2FSPAN%3E%3B%0A%3C%2FPRE%3E%0A%3C%2FDIV%3E%0A%3CP%3EWhen%20using%20dependency%20injection%2C%20Microsoft.Extensions.Log%20is%20configured%20implicitly%3A%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CDIV%20class%3D%22highlight%20highlight-source-cs%20notranslate%20position-relative%20overflow-auto%22%3E%0A%3CPRE%3E%20%20%20%20%20%20%20%20%3CSPAN%20class%3D%22pl-smi%22%3Eservices%3C%2FSPAN%3E.%3CSPAN%20class%3D%22pl-en%22%3EAddDbContext%3C%2FSPAN%3E%26lt%3B%3CSPAN%20class%3D%22pl-en%22%3EAdvWorksDbContext%3C%2FSPAN%3E%26gt%3B(%3CSPAN%20class%3D%22pl-en%22%3Eoptions%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3E%3D%26gt%3B%3C%2FSPAN%3E%20%7B%20%3CSPAN%20class%3D%22pl-smi%22%3Eoptions%3C%2FSPAN%3E%0A%20%20%20%20%20%20%20%20%20%20%20%20.%3CSPAN%20class%3D%22pl-en%22%3EUseSqlServer%3C%2FSPAN%3E(%3CSPAN%20class%3D%22pl-s%22%3E%3CSPAN%20class%3D%22pl-pds%22%3E%22%3C%2FSPAN%3EConfiguration%5B%3CSPAN%20class%3D%22pl-pds%22%3E%22%3C%2FSPAN%3E%3C%2FSPAN%3E%3CSPAN%20class%3D%22pl-en%22%3EConnectionStrings%3C%2FSPAN%3E%3A%3CSPAN%20class%3D%22pl-smi%22%3EDefault%3C%2FSPAN%3E%5D%3CSPAN%20class%3D%22pl-s%22%3E%3CSPAN%20class%3D%22pl-pds%22%3E%22%3C%2FSPAN%3E)%3CSPAN%20class%3D%22pl-ii%22%3E%3B%3C%2FSPAN%3E%3C%2FSPAN%3E%0A%20%20%20%20%20%20%20%20%7D)%3B%3C%2FPRE%3E%0A%3C%2FDIV%3E%0A%3CP%3EIn%20the%20appsettings.json%20file%20you%20can%20configure%20the%20desired%20log%20level%20for%20EF%20Core%3A%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CDIV%20class%3D%22highlight%20highlight-source-json%20notranslate%20position-relative%20overflow-auto%22%3E%0A%3CPRE%3E%7B%0A%20%20%3CSPAN%20class%3D%22pl-ent%22%3E%22Logging%22%3C%2FSPAN%3E%3A%20%7B%0A%20%20%20%20%3CSPAN%20class%3D%22pl-ent%22%3E%22LogLevel%22%3C%2FSPAN%3E%3A%20%7B%0A%20%20%20%20%20%20%3CSPAN%20class%3D%22pl-ent%22%3E%22Microsoft.EntityFrameworkCore%22%3C%2FSPAN%3E%3A%20%3CSPAN%20class%3D%22pl-s%22%3E%3CSPAN%20class%3D%22pl-pds%22%3E%22%3C%2FSPAN%3EInformation%3CSPAN%20class%3D%22pl-pds%22%3E%22%3C%2FSPAN%3E%3C%2FSPAN%3E%0A%20%20%20%20%7D%0A%20%20%7D%2C%0A%20%20%3CSPAN%20class%3D%22pl-ii%22%3E...%3C%2FSPAN%3E%3C%2FPRE%3E%0A%3C%2FDIV%3E%0A%3CP%3EA%20very%20useful%20feature%20for%20correlating%20queries%20in%20logs%20with%20code%20commands%20is%20the%20use%20of%20the%20TagWith%20function%20that%20makes%20it%20possible%20to%20add%20a%20comment%20to%20each%20command%3A%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CDIV%20class%3D%22highlight%20highlight-source-cs%20notranslate%20position-relative%20overflow-auto%22%3E%0A%3CPRE%3E%20%20%20%20%3CSPAN%20class%3D%22pl-k%22%3Evar%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-en%22%3Eqry%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3E%3D%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-smi%22%3Econtext%3C%2FSPAN%3E.%3CSPAN%20class%3D%22pl-smi%22%3ECustomers%3C%2FSPAN%3E.%3CSPAN%20class%3D%22pl-en%22%3ETagWith%3C%2FSPAN%3E(%3CSPAN%20class%3D%22pl-s%22%3E%3CSPAN%20class%3D%22pl-pds%22%3E%22%3C%2FSPAN%3ETraz%20todos%20os%20clientes%3CSPAN%20class%3D%22pl-pds%22%3E%22%3C%2FSPAN%3E%3C%2FSPAN%3E).%3C%2FPRE%3E%0A%3C%2FDIV%3E%0A%3CDIV%20class%3D%22snippet-clipboard-content%20notranslate%20position-relative%20overflow-auto%22%3E%0A%3CPRE%20class%3D%22notranslate%22%20lang%3D%22text%22%3E%3CCODE%3Einfo%3A%20Microsoft.EntityFrameworkCore.Database.Command%5B20101%5D%0A%20%20%20%20%20%20Executed%20DbCommand%20(22ms)%20%5BParameters%3D%5B%5D%2C%20CommandType%3D'Text'%2C%20CommandTimeout%3D'30'%5D%0A%20%20%20%20%20%20--%20Traz%20todos%20os%20clientes%0A%0A%20%20%20%20%20%20SELECT%20%5Bc%5D.%5BCustomerID%5D%2C%20%5Bc%5D.%5BCompanyName%5D%2C%20%5Bc%5D.%5BEmailAddress%5D%2C%20%5Bc%5D.%5BFirstName%5D%2C%20%5Bc%5D.%5BLastName%5D%2C%20%5Bc%5D.%5BMiddleName%5D%2C%20%5Bc%5D.%5BModifiedDate%5D%2C%20%5Bc%5D.%5BNameStyle%5D%2C%20%5Bc%5D.%5BPasswordHash%5D%2C%20%5Bc%5D.%5BPasswordSalt%5D%2C%20%5Bc%5D.%5BPhone%5D%2C%20%5Bc%5D.%5Browguid%5D%2C%20%5Bc%5D.%5BSalesPerson%5D%2C%20%5Bc%5D.%5BSuffix%5D%2C%20%5Bc%5D.%5BTitle%5D%0A%20%20%20%20%20%20FROM%20%5BSalesLT%5D.%5BCustomer%5D%20AS%20%5Bc%5D%0A%3C%2FCODE%3E%3C%2FPRE%3E%0A%3C%2FDIV%3E%0A%3CP%3EQueries%20with%20high%20execution%20time%20are%20the%20ones%20that%20should%20be%20investigated%20more%20thoroughly.%20If%20necessary%2C%20ask%20a%20database%20expert%20for%20help%20on%20how%20to%20identify%20the%20heaviest%20queries%20and%20actions%20to%20improve%20performance.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CBLOCKQUOTE%3E%0A%3CP%3E%3CSTRONG%3EAlways%20look%20at%20the%20generated%20queries!%3C%2FSTRONG%3E%3C%2FP%3E%0A%3C%2FBLOCKQUOTE%3E%0A%3CH3%20dir%3D%22auto%22%20id%3D%22toc-hId-1352845016%22%20id%3D%22toc-hId-1353709765%22%3E%3CA%20id%3D%22user-content-trazendo-s%C3%B3-o-necess%C3%A1rio%22%20class%3D%22anchor%22%20href%3D%22https%3A%2F%2Fgithub.com%2FAppInnovationBrazil%2Fblog%2Fblob%2Fmain%2Fdrafts%2Fef-core-perf%2F01.Assuma%2520o%2520controle.md%23trazendo-s%25C3%25B3-o-necess%25C3%25A1rio%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noreferrer%22%20aria-hidden%3D%22true%22%3E%3C%2FA%3EBringing%20only%20what%20is%20necessary%3C%2FH3%3E%0A%3CP%3EThe%20most%20basic%20rule%20to%20be%20respected%20when%20writing%20a%20query%20to%20any%20data%20source%20is%20to%20bring%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%3CSTRONG%3Eonly%20the%20data%20you%20are%20going%20to%20use%3C%2FSTRONG%3E.%20Do%20not%20write%20queries%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%3CSTRONG%3Ewithout%20a%20WHERE%20clause%3C%2FSTRONG%3E%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3Eand%20never%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%20write%3CSTRONG%3Equeries%20using%20SELECT*%3C%2FSTRONG%3E%2C%20remember%20that%20data%20must%20be%20transported%20over%20the%20network%20and%20mapped%20to%20class%20properties%20in%20code%2C%20and%20this%20takes%20time%20and%20consumes%20unnecessary%20resources.%20Less%20is%20more.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CDIV%20class%3D%22highlight%20highlight-source-cs%20notranslate%20position-relative%20overflow-auto%22%3E%0A%3CPRE%3E%3CSPAN%20class%3D%22pl-k%22%3Evar%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-en%22%3Eqry%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3E%3D%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-smi%22%3Econtext%3C%2FSPAN%3E.%3CSPAN%20class%3D%22pl-smi%22%3ECustomers%3C%2FSPAN%3E%3B%0A%0A%3CSPAN%20class%3D%22pl-k%22%3Eforeach%3C%2FSPAN%3E%20(%3CSPAN%20class%3D%22pl-k%22%3Evar%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-en%22%3Eitem%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3Ein%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-smi%22%3Eqry%3C%2FSPAN%3E)%20%7B%0A%20%20%20...%0A%7D%3C%2FPRE%3E%0A%3C%2FDIV%3E%0A%3CP%3EBased%20on%20this%20premise%2C%20what%20is%20the%20problem%20with%20the%20query%20of%20the%20example%20above%3F%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EIf%20we%20don't%20put%20it%20under%20a%20context%2C%20there's%20no%20problem.%20So%20let's%20stipulate%20a%20requirement%3A%20I%20need%20to%20get%20a%20list%20with%20Id%2C%20first%20and%20last%20name%20of%20all%20customers.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EIn%20this%20case%20the%20error%20becomes%20more%20evident%2C%20the%20query%20brings%20all%20the%20data%20from%20all%20clients.%20If%20the%20company%20has%20many%20customers%20(quite%20desirable%20situation)%20we%20can%20have%20long%20times%20to%20bring%20and%20map%20all%20the%20data.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EBy%20defining%20the%20object%20model%20for%20business%20entities%2C%20we%20create%20classes%20that%20actually%20map%20business%20domain%20information%20to%20code.%20This%20is%20perfect%20when%20you%20view%20details%20of%20an%20entity%20(a%20customer%20for%20example)%20or%20update%20the%20information%20in%20the%20database%2C%20but%20this%20is%20not%20ideal%20when%20you%20only%20need%20some%20data.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3ENot%20required%20to%20use%20all%20the%20properties%20of%20a%20class%20when%20making%20a%20query%2C%20LINQ%20offers%20the%20possibility%20of%20using%20projections%20that%20is%20the%20direct%20equivalent%20to%20a%20select%20with%20field%20list.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EThe%20example%20below%20uses%20the%20Select%20method%20with%20an%20anonymous%20type%20that%20contains%20only%20the%20data%20you%20want%3A%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CDIV%20class%3D%22highlight%20highlight-source-cs%20notranslate%20position-relative%20overflow-auto%22%3E%0A%3CPRE%3E%3CSPAN%20class%3D%22pl-k%22%3Evar%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-en%22%3Eqry%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3E%3D%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-smi%22%3Econtext%3C%2FSPAN%3E.%3CSPAN%20class%3D%22pl-smi%22%3ECustomers%3C%2FSPAN%3E.%3CSPAN%20class%3D%22pl-en%22%3ETagWith%3C%2FSPAN%3E(%3CSPAN%20class%3D%22pl-s%22%3E%3CSPAN%20class%3D%22pl-pds%22%3E%22%3C%2FSPAN%3ETraz%20apenas%20Id%2C%20nome%20e%20sobrenome%20dos%20clientes%3CSPAN%20class%3D%22pl-pds%22%3E%22%3C%2FSPAN%3E%3C%2FSPAN%3E)%0A%20%20%20%20.%3CSPAN%20class%3D%22pl-en%22%3ESelect%3C%2FSPAN%3E(%3CSPAN%20class%3D%22pl-en%22%3Ec%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3E%3D%26gt%3B%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3Enew%3C%2FSPAN%3E%20%7B%0A%20%20%20%20%20%20%20%20%20%3CSPAN%20class%3D%22pl-smi%22%3ECustomerId%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3E%3D%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-smi%22%3Ec%3C%2FSPAN%3E.%3CSPAN%20class%3D%22pl-smi%22%3ECustomerId%3C%2FSPAN%3E%2C%0A%20%20%20%20%20%20%20%20%20%3CSPAN%20class%3D%22pl-smi%22%3EFirstName%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3E%3D%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-smi%22%3Ec%3C%2FSPAN%3E.%3CSPAN%20class%3D%22pl-smi%22%3EFirstName%3C%2FSPAN%3E%2C%0A%20%20%20%20%20%20%20%20%20%3CSPAN%20class%3D%22pl-smi%22%3ELastName%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3E%3D%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-smi%22%3Ec%3C%2FSPAN%3E.%3CSPAN%20class%3D%22pl-smi%22%3ELastName%3C%2FSPAN%3E%0A%20%20%20%20%20%7D)%3B%3C%2FPRE%3E%0A%3C%2FDIV%3E%0A%3CP%3EImplicitly%20the%20compiler%20will%20define%20a%20class%20that%20represents%20the%20anonymous%20type.%20Here's%20the%20difference%20from%20the%20query%20generated%20in%20the%20log%3A%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CDIV%20class%3D%22snippet-clipboard-content%20notranslate%20position-relative%20overflow-auto%22%3E%0A%3CPRE%20class%3D%22notranslate%22%20lang%3D%22Text%22%3E%3CCODE%3Einfo%3A%20Microsoft.EntityFrameworkCore.Database.Command%5B20101%5D%0A%20%20%20%20%20%20Executed%20DbCommand%20(24ms)%20%5BParameters%3D%5B%5D%2C%20CommandType%3D'Text'%2C%20CommandTimeout%3D'30'%5D%0A%20%20%20%20%20%20--%20Traz%20apenas%20Id%2C%20nome%20e%20sobrenome%20dos%20clientes%0A%0A%20%20%20%20%20%20SELECT%20%5Bc%5D.%5BCustomerID%5D%20AS%20%5BCustomerId%5D%2C%20%5Bc%5D.%5BFirstName%5D%2C%20%5Bc%5D.%5BLastName%5D%0A%20%20%20%20%20%20FROM%20%5BSalesLT%5D.%5BCustomer%5D%20AS%20%5Bc%5D%0A%3C%2FCODE%3E%3C%2FPRE%3E%0A%3C%2FDIV%3E%0A%3CP%3EAnonymous%20types%20are%20good%20when%20used%20within%20the%20same%20method%2C%20but%20are%20not%20an%20option%20when%20you%20want%20to%20pass%20information%20to%20other%20methods%2C%20either%20as%20a%20parameter%20or%20as%20a%20return.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EFor%20these%20scenarios%20you%20can%20define%20specific%20classes%20with%20only%20the%20data%20that%20you%20want%20to%20obtain.%20E.g.%3A%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CDIV%20class%3D%22highlight%20highlight-source-cs%20notranslate%20position-relative%20overflow-auto%22%3E%0A%3CPRE%3E%20%20%20%20...%0A%20%20%20%20%3CSPAN%20class%3D%22pl-k%22%3Einternal%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3Eclass%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-en%22%3EMinimalCustomer%3C%2FSPAN%3E%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20%3CSPAN%20class%3D%22pl-k%22%3Epublic%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3Eint%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-en%22%3ECustomerId%3C%2FSPAN%3E%20%7B%20%3CSPAN%20class%3D%22pl-k%22%3Eget%3C%2FSPAN%3E%3B%20%3CSPAN%20class%3D%22pl-k%22%3Eset%3C%2FSPAN%3E%3B%20%7D%0A%20%20%20%20%20%20%20%20%3CSPAN%20class%3D%22pl-k%22%3Epublic%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3Estring%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-en%22%3EFirstName%3C%2FSPAN%3E%20%7B%20%3CSPAN%20class%3D%22pl-k%22%3Eget%3C%2FSPAN%3E%3B%20%3CSPAN%20class%3D%22pl-k%22%3Eset%3C%2FSPAN%3E%3B%20%7D%0A%20%20%20%20%20%20%20%20%3CSPAN%20class%3D%22pl-k%22%3Epublic%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3Estring%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-en%22%3ELastName%3C%2FSPAN%3E%20%7B%20%3CSPAN%20class%3D%22pl-k%22%3Eget%3C%2FSPAN%3E%3B%20%3CSPAN%20class%3D%22pl-k%22%3Eset%3C%2FSPAN%3E%3B%20%7D%0A%20%20%20%20%7D%0A%20%20%20%20...%0A%20%20%20%20%3CSPAN%20class%3D%22pl-k%22%3Evar%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-en%22%3Eqry%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3E%3D%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-smi%22%3Econtext%3C%2FSPAN%3E.%3CSPAN%20class%3D%22pl-smi%22%3ECustomers%3C%2FSPAN%3E%0A%20%20%20%20%20%20%20%20.%3CSPAN%20class%3D%22pl-en%22%3ESelect%3C%2FSPAN%3E(%3CSPAN%20class%3D%22pl-en%22%3Ec%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3E%3D%26gt%3B%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3Enew%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-en%22%3EMinimalCustomer%3C%2FSPAN%3E%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20%3CSPAN%20class%3D%22pl-smi%22%3ECustomerId%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3E%3D%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-smi%22%3Ec%3C%2FSPAN%3E.%3CSPAN%20class%3D%22pl-smi%22%3ECustomerId%3C%2FSPAN%3E%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%3CSPAN%20class%3D%22pl-smi%22%3EFirstName%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3E%3D%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-smi%22%3Ec%3C%2FSPAN%3E.%3CSPAN%20class%3D%22pl-smi%22%3EFirstName%3C%2FSPAN%3E%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%3CSPAN%20class%3D%22pl-smi%22%3ELastName%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3E%3D%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-smi%22%3Ec%3C%2FSPAN%3E.%3CSPAN%20class%3D%22pl-smi%22%3ELastName%3C%2FSPAN%3E%0A%20%20%20%20%20%20%20%20%7D)%3B%0A%20%20%20%20...%3C%2FPRE%3E%0A%3C%2FDIV%3E%0A%3CP%3EProjections%20solve%20the%20question%20of%20bringing%20only%20the%20necessary%20columns%2C%20bringing%20only%20the%20necessary%20rows%20is%20where%3CSTRONG%3Efunction%3C%2FSTRONG%3E%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E.%20Whenever%20possible%2C%20generate%20queries%20with%20filter%20criteria%2C%20remember%20that%20the%20database%20can%20grow%20over%20time.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EFor%20example%2C%20we%20can%20only%20bring%20in%20customer%20data%20that%20is%20served%20by%20the%20seller%20who%20is%20currently%20using%20the%20application.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CDIV%20class%3D%22highlight%20highlight-source-cs%20notranslate%20position-relative%20overflow-auto%22%3E%0A%3CPRE%3E%20%20%3CSPAN%20class%3D%22pl-k%22%3Evar%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-en%22%3EcurrentUser%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3E%3D%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-s%22%3E%3CSPAN%20class%3D%22pl-pds%22%3E%22%3C%2FSPAN%3Eadventure-works%3CSPAN%20class%3D%22pl-cce%22%3E%5C%5C%3C%2FSPAN%3Edavid8%3CSPAN%20class%3D%22pl-pds%22%3E%22%3C%2FSPAN%3E%3C%2FSPAN%3E%3B%0A%20%20%3CSPAN%20class%3D%22pl-k%22%3Evar%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-en%22%3Eqry%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3E%3D%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-smi%22%3Econtext%3C%2FSPAN%3E.%3CSPAN%20class%3D%22pl-smi%22%3ECustomers%3C%2FSPAN%3E%0A%20%20%20%20%20%20.%3CSPAN%20class%3D%22pl-en%22%3EWhere%3C%2FSPAN%3E(%3CSPAN%20class%3D%22pl-en%22%3Ec%3C%2FSPAN%3E%3CSPAN%20class%3D%22pl-k%22%3E%3D%26gt%3B%3C%2FSPAN%3E%3CSPAN%20class%3D%22pl-smi%22%3Ec%3C%2FSPAN%3E.%3CSPAN%20class%3D%22pl-smi%22%3ESalesPerson%3C%2FSPAN%3E%3CSPAN%20class%3D%22pl-k%22%3E%3D%3D%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-smi%22%3EcurrentUser%3C%2FSPAN%3E)%0A%20%20%20%20%20%20.%3CSPAN%20class%3D%22pl-en%22%3ESelect%3C%2FSPAN%3E(%3CSPAN%20class%3D%22pl-en%22%3Ec%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3E%3D%26gt%3B%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3Enew%3C%2FSPAN%3E%20%7B%0A%20%20%20%20%20%20%20%20%20%20%3CSPAN%20class%3D%22pl-smi%22%3ECustomerId%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3E%3D%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-smi%22%3Ec%3C%2FSPAN%3E.%3CSPAN%20class%3D%22pl-smi%22%3ECustomerId%3C%2FSPAN%3E%2C%0A%20%20%20%20%20%20%20%20%20%20%3CSPAN%20class%3D%22pl-smi%22%3EFirstName%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3E%3D%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-smi%22%3Ec%3C%2FSPAN%3E.%3CSPAN%20class%3D%22pl-smi%22%3EFirstName%3C%2FSPAN%3E%2C%0A%20%20%20%20%20%20%20%20%20%20%3CSPAN%20class%3D%22pl-smi%22%3ELastName%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3E%3D%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-smi%22%3Ec%3C%2FSPAN%3E.%3CSPAN%20class%3D%22pl-smi%22%3ELastName%3C%2FSPAN%3E%0A%20%20%20%20%20%20%7D)%3B%3C%2FPRE%3E%0A%3C%2FDIV%3E%0A%3CP%3EThe%20%3CSTRONG%3EWhere%20method%3C%2FSTRONG%3E%20appends%20the%20%3CSTRONG%3EWHERE%20clause%3C%2FSTRONG%3E%20in%20the%20SQL%20query%20and%20uses%20parameters%20to%20make%20SQL%20injection%20difficult%3A%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CDIV%20class%3D%22snippet-clipboard-content%20notranslate%20position-relative%20overflow-auto%22%3E%0A%3CPRE%20class%3D%22notranslate%22%20lang%3D%22Text%22%3E%3CCODE%3Einfo%3A%20Microsoft.EntityFrameworkCore.Database.Command%5B20101%5D%0A%20%20%20%20%20%20Executed%20DbCommand%20(30ms)%20%5BParameters%3D%5B%40__currentUser_0%3D'%3F'%20(Size%20%3D%20256)%5D%2C%20CommandType%3D'Text'%2C%20CommandTimeout%3D'30'%5D%0A%20%20%20%20%20%20SELECT%20%5Bc%5D.%5BCustomerID%5D%20AS%20%5BCustomerId%5D%2C%20%5Bc%5D.%5BFirstName%5D%2C%20%5Bc%5D.%5BLastName%5D%0A%20%20%20%20%20%20FROM%20%5BSalesLT%5D.%5BCustomer%5D%20AS%20%5Bc%5D%0A%20%20%20%20%20%20WHERE%20%5Bc%5D.%5BSalesPerson%5D%20%3D%20%40__currentUser_0%0A%3C%2FCODE%3E%3C%2FPRE%3E%0A%3C%2FDIV%3E%0A%3CP%3EIf%20you%20cannot%20force%20the%20use%20of%20query%20filters%20in%20the%20application%2C%20you%20can%20limit%20the%20number%20of%20results%20returned.%20Most%20of%20the%20time%20it%20makes%20no%20sense%20to%20return%20thousands%20or%20millions%20of%20lines.%20The%20Take%20method%20can%20be%20used%20to%20place%20a%20limiter%3A%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CDIV%20class%3D%22highlight%20highlight-source-cs%20notranslate%20position-relative%20overflow-auto%22%3E%0A%3CPRE%3E%20%20%3CSPAN%20class%3D%22pl-k%22%3Evar%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-en%22%3Eqry%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3E%3D%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-smi%22%3Econtext%3C%2FSPAN%3E.%3CSPAN%20class%3D%22pl-smi%22%3ECustomers%3C%2FSPAN%3E%0A%20%20%20%20%20%20.%3CSPAN%20class%3D%22pl-en%22%3EWhere%3C%2FSPAN%3E(%3CSPAN%20class%3D%22pl-en%22%3Ec%3C%2FSPAN%3E%3CSPAN%20class%3D%22pl-k%22%3E%3D%26gt%3B%3C%2FSPAN%3E%3CSPAN%20class%3D%22pl-smi%22%3Ec%3C%2FSPAN%3E.%3CSPAN%20class%3D%22pl-smi%22%3ESalesPerson%3C%2FSPAN%3E%3CSPAN%20class%3D%22pl-k%22%3E%3D%3D%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-smi%22%3EcurrentUser%3C%2FSPAN%3E)%0A%20%20%20%20%20%20.%3CSPAN%20class%3D%22pl-en%22%3ESelect%3C%2FSPAN%3E(%3CSPAN%20class%3D%22pl-en%22%3Ec%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3E%3D%26gt%3B%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3Enew%3C%2FSPAN%3E%20%7B%0A%20%20%20%20%20%20%20%20%20%20%3CSPAN%20class%3D%22pl-smi%22%3ECustomerId%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3E%3D%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-smi%22%3Ec%3C%2FSPAN%3E.%3CSPAN%20class%3D%22pl-smi%22%3ECustomerId%3C%2FSPAN%3E%2C%0A%20%20%20%20%20%20%20%20%20%20%3CSPAN%20class%3D%22pl-smi%22%3EFirstName%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3E%3D%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-smi%22%3Ec%3C%2FSPAN%3E.%3CSPAN%20class%3D%22pl-smi%22%3EFirstName%3C%2FSPAN%3E%2C%0A%20%20%20%20%20%20%20%20%20%20%3CSPAN%20class%3D%22pl-smi%22%3ELastName%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-k%22%3E%3D%3C%2FSPAN%3E%20%3CSPAN%20class%3D%22pl-smi%22%3Ec%3C%2FSPAN%3E.%3CSPAN%20class%3D%22pl-smi%22%3ELastName%3C%2FSPAN%3E%0A%20%20%20%20%20%20%7D)%0A%20%20%20%20%20%20.%3CSPAN%20class%3D%22pl-en%22%3EOrderBy%3C%2FSPAN%3E(%3CSPAN%20class%3D%22pl-en%22%3Ec%3C%2FSPAN%3E%3CSPAN%20class%3D%22pl-k%22%3E%3D%26gt%3B%3C%2FSPAN%3E%3CSPAN%20class%3D%22pl-smi%22%3Ec%3C%2FSPAN%3E.%3CSPAN%20class%3D%22pl-smi%22%3ELastName%3C%2FSPAN%3E)%0A%20%20%20%20%20%20.%3CSPAN%20class%3D%22pl-en%22%3ETake%3C%2FSPAN%3E(%3CSPAN%20class%3D%22pl-c1%22%3E100%3C%2FSPAN%3E)%3B%3C%2FPRE%3E%0A%3C%2FDIV%3E%0A%3CDIV%20class%3D%22snippet-clipboard-content%20notranslate%20position-relative%20overflow-auto%22%3E%0A%3CPRE%20class%3D%22notranslate%22%20lang%3D%22Text%22%3E%3CCODE%3Einfo%3A%20Microsoft.EntityFrameworkCore.Database.Command%5B20101%5D%0A%20%20%20%20%20%20Executed%20DbCommand%20(26ms)%20%5BParameters%3D%5B%40__p_1%3D'%3F'%20(DbType%20%3D%20Int32)%2C%20%40__currentUser_0%3D'%3F'%20(Size%20%3D%20256)%5D%2C%20CommandType%3D'Text'%2C%20CommandTimeout%3D'30'%5D%0A%20%20%20%20%20%20SELECT%20TOP(%40__p_1)%20%5Bc%5D.%5BCustomerID%5D%20AS%20%5BCustomerId%5D%2C%20%5Bc%5D.%5BFirstName%5D%2C%20%5Bc%5D.%5BLastName%5D%0A%20%20%20%20%20%20FROM%20%5BSalesLT%5D.%5BCustomer%5D%20AS%20%5Bc%5D%0A%20%20%20%20%20%20WHERE%20%5Bc%5D.%5BSalesPerson%5D%20%3D%20%40__currentUser_0%0A%20%20%20%20%20%20ORDER%20BY%20%5Bc%5D.%5BLastName%5D%0A%3C%2FCODE%3E%3C%2FPRE%3E%0A%3C%2FDIV%3E%0A%3CP%3ENote%20in%20the%20previous%20example%20the%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%3CSTRONG%3ETake%3C%2FSTRONG%3E%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3Emethod%20inserts%20the%20%3CSTRONG%3ETOP%20clause%20into%3C%2FSTRONG%3E%20the%20SQL%20command.%20The%20use%20of%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%3CSTRONG%3EOrderBy%3C%2FSTRONG%3E%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3Eis%20to%20ensure%20the%20order%20of%20the%20results.%20If%20omitted%20we%20will%20have%20alerts%20in%20the%20log%20indicating%20that%20there%20is%20no%20guarantee%20of%20order%20in%20the%20results%20of%20SQL%20commands%20without%20specifying%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%3CSTRONG%3EORDER%20BY%3C%2FSTRONG%3E%3A%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CDIV%20class%3D%22snippet-clipboard-content%20notranslate%20position-relative%20overflow-auto%22%3E%0A%3CPRE%20class%3D%22notranslate%22%20lang%3D%22Text%22%3E%3CCODE%3Ewarn%3A%20Microsoft.EntityFrameworkCore.Query%5B10102%5D%0A%20%20%20%20%20%20The%20query%20uses%20a%20row%20limiting%20operator%20('Skip'%2F'Take')%20without%20an%20'OrderBy'%20operator.%20This%20may%20lead%20to%20unpredictable%20results.%20If%20the%20'Distinct'%20operator%20is%20used%20after%20'OrderBy'%2C%20then%20make%20sure%20to%20use%20the%20'OrderBy'%20operator%20after%20'Distinct'%20as%20the%20ordering%20would%20otherwise%20get%20erased.%0A%3C%2FCODE%3E%3C%2FPRE%3E%0A%3C%2FDIV%3E%0A%3CH3%20dir%3D%22auto%22%20id%3D%22toc-hId--454609447%22%20id%3D%22toc-hId--453744698%22%3E%26nbsp%3B%3C%2FH3%3E%0A%3CH3%20dir%3D%22auto%22%20id%3D%22toc-hId-2032903386%22%20id%3D%22toc-hId-2033768135%22%3E%3CA%20id%3D%22user-content-finalizando%22%20class%3D%22anchor%22%20href%3D%22https%3A%2F%2Fgithub.com%2FAppInnovationBrazil%2Fblog%2Fblob%2Fmain%2Fdrafts%2Fef-core-perf%2F01.Assuma%2520o%2520controle.md%23finalizando%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noreferrer%22%20aria-hidden%3D%22true%22%3E%3C%2FA%3EEnding%3C%2FH3%3E%0A%3CP%3EFrameworks%20exist%20to%20make%20the%20job%20easier%2C%20but%20it%20is%20the%20programmer's%20responsibility%20to%20understand%20what%20they%20do%20and%20use%20them%20in%20the%20best%20way.%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%3CSTRONG%3EBe%20in%20control%3C%2FSTRONG%3E.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3E%3CSTRONG%3EAlways%20bring%20only%20the%20necessary%20data%3C%2FSTRONG%3E%2C%20even%20if%20it%20means%20writing%20a%20little%20more%20code.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3E%3CSTRONG%3ELearn%20SQL%3C%2FSTRONG%3E%2C%20it's%20urban%20legend%20this%20story%20that%20ORM%20frees%20us%20from%20knowing%20SQL.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3ETest%20with%20masses%20of%20data%20that%20reproduce%20the%20expected%20scenarios%20in%20production%20or%20if%20possible%20that%20exceed%20those%20scenarios.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EIn%20the%20case%20of%20EF%20Core%20or%20any%20other%20ORM%20framework%2C%20you%20need%20to%20analyze%20the%20generated%20queries.%20At%20least%20the%20most%20critical.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EThere%20are%20other%20tools%20that%20can%20be%20used%20to%20understand%20and%20optimize%20SQL%20commands%2C%20I%20recommend%20installing%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%3CSTRONG%3EAzure%20Data%20Studio%3C%2FSTRONG%3E%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3Ethat%20allows%20you%20to%20connect%20to%20databases%2C%20execute%20commands%2C%20investigate%20access%20plans%20between%20various%20functions.%20It%20is%20possible%20to%20extend%20the%20functionality%20of%20the%20tool%20through%20extensions%20and%20one%20that%20I%20recommend%20to%20understand%20what%20happens%20behind%20THE%20ORM%20is%20the%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%3CSTRONG%3ESQL%20Server%20Profiler%3C%2FSTRONG%3E.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CH3%20dir%3D%22auto%22%20id%3D%22toc-hId-225448923%22%20id%3D%22toc-hId-226313672%22%3E%3CA%20id%3D%22user-content-refer%C3%AAncias%22%20class%3D%22anchor%22%20href%3D%22https%3A%2F%2Fgithub.com%2FAppInnovationBrazil%2Fblog%2Fblob%2Fmain%2Fdrafts%2Fef-core-perf%2F01.Assuma%2520o%2520controle.md%23refer%25C3%25AAncias%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noreferrer%22%20aria-hidden%3D%22true%22%3E%3C%2FA%3EReferences%3C%2FH3%3E%0A%3CUL%20dir%3D%22auto%22%3E%0A%3CLI%3E%3CA%20href%3D%22https%3A%2F%2Fdocs.microsoft.com%2Fef%2Fcore%2Flogging-events-diagnostics%2F%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noreferrer%22%3ELogging%20and%20interception%20overview%3C%2FA%3E%3C%2FLI%3E%0A%3CLI%3E%3CA%20href%3D%22https%3A%2F%2Fdocs.microsoft.com%2Fef%2Fcore%2Fperformance%2Fperformance-diagnosis%3Ftabs%3Dsimple-logging%252Cload-entities%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noreferrer%22%3EPerformance%20diagnostics%3C%2FA%3E%3C%2FLI%3E%0A%3CLI%3E%3CA%20href%3D%22https%3A%2F%2Fdocs.microsoft.com%2Fsql%2Fazure-data-studio%2Fdownload-azure-data-studio%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noreferrer%22%3EDownload%20and%20install%20Azure%20Data%20Studio%3C%2FA%3E%3C%2FLI%3E%0A%3C%2FUL%3E%3C%2FLINGO-BODY%3E%3CLINGO-TEASER%20id%3D%22lingo-teaser-3408195%22%20slang%3D%22pt-BR%22%3E%3CP%3E%3CSPAN%20class%3D%22lia-inline-image-display-wrapper%20lia-image-align-inline%22%20image-alt%3D%22MSC19_renaultRacingFactory_022%20(Small).jpg%22%20style%3D%22width%3A%20721px%3B%22%3E%3CIMG%20src%3D%22https%3A%2F%2Ftechcommunity.microsoft.com%2Ft5%2Fimage%2Fserverpage%2Fimage-id%2F373834iAE9DF765D441B110%2Fimage-size%2Flarge%3Fv%3Dv2%26amp%3Bpx%3D999%22%20role%3D%22button%22%20title%3D%22MSC19_renaultRacingFactory_022%20(Small).jpg%22%20alt%3D%22MSC19_renaultRacingFactory_022%20(Small).jpg%22%20%2F%3E%3C%2FSPAN%3E%3C%2FP%3E%0A%3CP%3EFirst%20article%20in%20a%20series%20whose%20proposal%20is%20to%20explore%20the%20Entity%20Framework%20Core%20from%20the%20performance%20aspect%20of%20data%20access.%26nbsp%3B%3C%2FP%3E%3C%2FLINGO-TEASER%3E%3CLINGO-LABS%20id%3D%22lingo-labs-3408195%22%20slang%3D%22pt-BR%22%3E%3CLINGO-LABEL%3EDevelopers%3C%2FLINGO-LABEL%3E%3CLINGO-LABEL%3Edotnet%3C%2FLINGO-LABEL%3E%3C%2FLINGO-LABS%3E
Co-Authors
Version history
Last update:
‎May 20 2022 03:59 PM
Updated by: