How to do a row count (SELECT COUNT) in Linq

7

How to make a count of records that a query would return in Linq (Entity Framework) in C #? The equivalent in SQL is to make a SELECT COUNT(*) .

Note that I want to receive the direct count of records, just like a SELECT COUNT (*) would do, and not receive the results and do a count afterwards. So a .Select().Count() or .Where().Count() does not solve my situation. Not even that:

var result = from tbl in tabela
             select tabela;
int contagem = result.Count();

How would you do other operations in a single query, for example: Min, Max, or arithmetic operations between two queries (ex: SELECT(...)/SELECT COUNT(*) )?

    
asked by anonymous 21.03.2014 / 15:22

2 answers

8

Although the commands are on separate lines in C #, only a query will be made to the database at the time you call the Count() method.

This tag only does one query :

var result = from tbl in tabela
             select tabela; // nenhuma query será executada

int contagem = result.Count(); // a query será executada aqui
    
21.03.2014 / 15:28
4

Basically for you to understand, while the list you are querying is a IQueryable and the Entity Framework has not executed any query to the database EF will try to convert your query into an SQL expression.

If you are using version 6 of the Entity Framework a good alternative is to always display the SQL queries executed by the framework, for example:

var db = new DataContext(); //sua instância da implementação DbContext
db.Database.Log = (s) => System.Diagnostics.Debug.Write(s); // essa linha seta que o log gerado pelo EF6 será exibido no Output do Visual Studio
var c = db.Produtos.Sum(m => m.PrecoCusto); // essa consulta será executada conforme sua pergunta, com um SUM(campo) na query SQL

Checking Database.Log you will be able to understand naturally what they are and when the EF actually executes a query in the database.

    
21.03.2014 / 15:47