简体   繁体   English

将查询从SQL转换为LINQ

[英]Convert query from SQL to LINQ

I need to convert this SQL query to LINQ: 我需要将此SQL查询转换为LINQ:

SELECT COUNT(result1.Id) AS total, 
    result1.OccurrenceDate, 
    result1.Path, 
    result1.Message, 
    result1.StackTrace 
FROM (SELECT * FROM tbllog ORDER BY OccurrenceDate DESC) AS result1
GROUP BY result1.Path, result1.Message ORDER BY total DESC

But I'm not getting success. 但是我没有成功。 I've tried in so many ways, nothing works. 我已经尝试了很多方法,但没有任何效果。 Some help? 一些帮助?

Create a linq query out of the following: 根据以下内容创建linq查询:

SELECT * FROM tbllog ORDER BY OccurrenceDate DESC AS result1
GROUP BY result1.Path, result1.Message ORDER BY total DESC

Once that is done, write some linq to get your counts. 完成后,编写一些linq即可计数。

var results = _dbContext.tbllog
    .GroupBy( t => new { t.Path, t.Message })
    .Select( g => new 
        {
            Total = g.Count(),
            Path = g.Key.Path,
            Message = g.Key.Message
        }).OrderBy(p => p.Total);

It is worth to mention that your sql query is invalid because the properties OccurrenceDate and StackTrace is not in the GROUP BY clause nor with in an aggregate function, therefore it is invalid query. 值得一提的是,您的sql查询无效,因为OccurrenceDateStackTrace属性不在GROUP BY子句中,也不在聚合函数中,因此它是无效查询。 The same with the LINQ query. 与LINQ查询相同。 You should determine what you want to do with them. 您应该确定要对他们做什么。 Either include them in the group by or use an aggregate function to select the appropriate value for each group. 可以将它们包含在组中,也可以使用聚合函数为每个组选择适当的值。

I don't know what the context is for your question, but if you don't need to modify the query such that it executes with additional parameters, I would highly recommend executing the query as SQL. 我不知道您的问题的上下文是什么,但是如果您不需要修改查询以使其具有其他参数即可执行,我强烈建议您将查询作为SQL执行。 This is supported on all the ORMs that I am aware of (Entity Framework, NHiberate, LINQ to SQL, etc). 我知道的所有ORM(实体框架,NHiberate,LINQ to SQL等)都支持此功能。

Erick 埃里克

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM