Sql server 2008 等价LINQ查询

Sql server 2008 等价LINQ查询,sql-server-2008,linq-to-sql,Sql Server 2008,Linq To Sql,我为SQL Server 2008中的学生提供了一个历史表 StudentHistoryId, StudentId, Grade, CreatedAt, ModifiedAt, ModifiedBy, Active 我是LINQ的新手 如何编写LINQ查询以获取所有活动学生的最新修改行以及相同学生的等效sql查询?LINQ var tempresult = (from student in Students where Active == true).O

我为SQL Server 2008中的学生提供了一个
历史

StudentHistoryId, StudentId, Grade, CreatedAt, ModifiedAt, ModifiedBy, Active
我是LINQ的新手

如何编写LINQ查询以获取所有活动学生的最新修改行以及相同学生的等效sql查询?

LINQ

 var tempresult = (from student in Students
                   where Active == true).OrderByDesc(ModifiedAt)
 List<Student> results = new List<Student>();
 foreach(var result in tempResult)
 {
    if((results.Where(r => r.StudentId == result.StudentId).FirstOrDefault()) == null)
    {
       results.Add(result);
    }
 }
Linq是有问题的(我肯定有更好的方法,但我记不起来了),我只对SQL语法有点信心(尽管它应该为您指明正确的方向,即使它不完全正确),但它们中的任何一个都应该得到:当前活动的每个学生的最大修改量

.FirstOrDefault()[LINQ]或Top 1将仅选择具有最新修改数据的单行(仅一个学生)。

类似于(假设为LINQ-SQL):

这是假设你想要所有的学生,不管他们是否有任何历史。如果不想这样做,可以从历史记录表开始,并按学生ID分组


要查看SQL,可以在调试中悬停变量以查看生成的SQL。我懒得转换LINQ;-)

你打算用哪种口味的Linq??Linq到SQL?Linq到实体(实体框架)?我尝试了sql查询,但它没有给出我想要的结果。我希望每个学生都有一条记录,只需将要分组的列添加到匿名类型即可。
 Select [Rows]
 From Students S
 Where S.Active = 1
 And S.ModifiedAt = (Select Max(ModifiedAt) 
                     From Student S1
                     Where S1.StudentId = S.StudentId)
using (YourDataContext db = new YourDataContext())
{
   var data = from s in db.Students
              select new 
              {
                  StudentId = s.StudentId,
                  LastHistory = s.Histories
                                 .OrderByDescending(s => s.ModifiedAt)
                                 .Where(s => s.Active)
                                 .FirstOrDefault()
              };
}
var q = 
    from h in history 
    where h.Active
    group h by new { h.StudentId, h.Grade } into g
    select new 
    {
        StudentId = g.Key.StudentId,
        Grade = g.Key.Grade,
        LatestModified = g.Max (x => x.ModifiedAt)
    }