linq2sql - 如何使用原始SQL从DB获取计数?

时间:2014-02-26 20:02:59

标签: c# .net asp.net-mvc linq-to-sql

目前,为了获得带有连接的复杂查询中的项目计数,我正在做这样的事情 -

string q = @"SELECT f.FILE_ID
           FROM [Email.Link] AS l INNER JOIN Email AS e ON (l.EMAIL_ID = e.EMAIL_ID)
           INNER JOIN File AS f ON (e.EMAIL_ID = f.EMAIL_ID)
           WHERE l.EntityId = 123";

var files = Context.ExecuteQuery<File>(q);
return files.Count();

任何更好的方法来做到这一点,而不是让所有的ID都回来计算? 我更愿意做一个SELECT Count(*)并在linq中获得int。

2 个答案:

答案 0 :(得分:1)

您可以将准备好的FILE_ID作为SQL查询的一部分返回,而不是返回COUNT集合:

        string q = @"SELECT COUNT(f.FILE_ID)
        FROM [Email.Link] AS l INNER JOIN Email AS e ON (l.EMAIL_ID = e.EMAIL_ID)
        INNER JOIN File AS f ON (e.EMAIL_ID = f.EMAIL_ID)
        WHERE l.EntityId = 123";

       return Context.ExecuteQuery<Int32>(q);

答案 1 :(得分:0)

试试这个

    string q = @"SELECT COUNT(f.FILE_ID)
    FROM [Email.Link] AS l INNER JOIN Email AS e ON (l.EMAIL_ID = e.EMAIL_ID)
    INNER JOIN File AS f ON (e.EMAIL_ID = f.EMAIL_ID)
    WHERE l.EntityId = 123";

   return Context.ExecuteQuery<Int32>(q).FirstOrDefault();