In ADO. NET Entity Framework 4, the SQL statement generated by the LINQ to entities statement that queries the number of records actually contains subqueries.
>>> Query code using Entity Framework 4:
using (SpaceObjectContext context = new SpaceObjectContext())
{
return context.SiteMsgs.Count(msg => msg.SenderSpaceUserId == 1);
}
>>> Generated SQL statement:
SELECT
[GroupBy1].[A1] AS [C1]
FROM ( SELECT
COUNT(1) AS [A1]
FROM [dbo].[club_Message] AS [Extent1]
WHERE 1 = [Extent1].[SenderID]
) AS [GroupBy1]
However, this problem does not exist in LINQ to SQL:
>>> Query using LINQ to SQL:
using(club_CNBlogsDataContext context = new club_CNBlogsDataContext())
{
return context.club_Messages.Count(msg => msg.SenderID == 1);
}
>>> Generated SQL statement:
exec sp_executesql N'SELECT COUNT(*) AS [value]
FROM [dbo].[club_Message] AS [t0]
WHERE [t0].[SenderID] = @p0',N'@p0 int',@p0=1