将SQL转换为Linq查询

时间:2016-10-14 12:36:19

标签: c# sql linq sql-to-linq-conversion

我试图将以下查询的输出转换为Linq查询

SELECT SearchQueries.Query,
       Clicks.Name,
       COUNT (SearchQueries.Query) AS Hits
FROM SearchQueries
INNER JOIN Clicks ON Clicks.SearchqueryId = SearchQueries.Id
GROUP BY SearchQueries.Query, Clicks.Name
ORDER BY Hits DESC

但我似乎无法弄清楚如何做到这一点; 这就是我到目前为止所拥有的

var result =
    _db.Clicks.Select(q => q)
        .GroupBy(q => q.Name, g => g.Searchquery.Query)
        .ToDictionary(g=> g.Key, g => g);

但我将如何继续?

结果是这样的:

+---------------+-------------------+------+
|Query          | Name              | Hits |
+---------------+-------------------+------+
|tag            | dnfsklmfnsd       | 53   |
|tag2           | dgsqfsdf          | 17   |
+---------------+-------------------+------+

原始表格如下所示

SearchQueries

+---+-------+
|Id | Query |
+---+-------+
| 1 | tag   | x 53
| 2 | tag2  | x 17
+---+-------+

点击次数

+---+-------------------+---------------+
|Id | Name              | SearchqueryId |
+---+-------------------+---------------+
| 1 | dnfsklmfnsd       | 1             |
| 2 | dgsqfsdf          | 2             |
+---+-------------------+---------------+

2 个答案:

答案 0 :(得分:1)

尝试使用GroupByCount :(我将命令更改为在表达式中使用SearchQueries作为“基表”,只是为了更容易与SQL进行比较语句来)

var result =
    _db.SearchQueries
       .GroupBy(sq => new { name = sq.Clicks.Name, query = sq.Query)
       .Select(sq => new {
                           Query = sq.Query,
                           Name = sq.Clicks.Name,
                           Hits = sq.Count()
                         })
       .OrderByDescending(sq => sq.Hits);

答案 1 :(得分:0)

好吧,如果你有一个导航属性Searchquery on Click,你可以这样做

$listImages