LinqToSql Count

You can pass the results of a linq query to the next statement like this one

var q = context.Products
                .Where(p => p.ProductName.StartsWith(“A”))
                .Count();
and that should provide the count of products with names starting with “A”. 
Further it would make no difference (performance wise) to skip theWhere statement and simply call the Count with filter as parameter, like:
var q = context.Products
                .Count(p => p.ProductName.StartsWith(“B”));
or in another syntax like:
    q = (from p in context.Products
         where p.ProductName.StartsWith(“C”)
         select true).Count();
So, I did put a tracing into the Context.Log to see what it goes to the SQL-Server. I’ve got the following for all three cases:
SELECT COUNT(*) AS [value]
FROM [dbo].[Products] AS [t0]
WHERE [t0].[ProductName] LIKE @p0
— @p0: Input NVarChar (Size = 4000; Prec = 0; Scale = 0) [A%]
— Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 4.0.30319.1

Author: Pouya Panahy

Microsoft certified DevOps engineer with passion in analysing, designing and implementing solutions for Azure Cloud with hands-on experience in security and quality assurence.

Leave a Reply