【问题标题】:Convert SQL query to Entity Framework which used AggregateFunctions and Where clause将 SQL 查询转换为使用 AggregateFunctions 和 Where 子句的实体框架
【发布时间】:2025-11-27 17:40:01
【问题描述】:

如何将此查询转换为实体框架?

SQL 查询:

SELECT Fullname, SUM(CoinCount+DiamondCount) AS GeneralPoint
FROM Students, Groups
WHERE Students.GroupId = Groups.Id AND Groups.Name = 'FSDA_1813_az'
GROUP BY Fullname
ORDER BY GeneralPoint

实体:

public class Student
{
    public int Id { get; set; }
    public int GroupId { get; set; }
    public string Fullname { get; set; }
    public Nullable<int> DiamondCount { get; set; }
    public Nullable<int> CoinCount { get; set; }
    public string Phone { get; set; }
    public string Address { get; set; }
    public string Education { get; set; }
    public string Email { get; set; }
    public System.DateTime Birthdate { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public Nullable<System.DateTime> LastVisited { get; set; }
    public string Facebook { get; set; }
    public string Linkedin { get; set; }
    public string SocialMedia { get; set; }
    public byte[] Photo { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Comment> Comments { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Exam> Exams { get; set; }
    public virtual Group Group { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Point> Points { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<StudentHomework> StudentHomeworks { get; set; }
}

用户存储库:

public ICollection<Student> GetUsersForGroup(string group)
{
    using (var db = new EFContext())
    {
        var temp = db.Students.Where(x => x.Group.Name == group).ToList();

        // I have to sort students in group by their DiamondCount+CoinCount as new GeneralCount
        temp = temp.OrderBy(x => );
    }
}

我必须根据学生的一般观点对学生进行排序(DiamondCount+CoinCount)。 但我无法使用实体框架发送 LINQ 查询。我该怎么做?

【问题讨论】:

  • I can't send SQL query - 因为你过早地调用ToList()
  • @GSerg 我想解释一下如何使用 LINQ 编写此查询。已更新
  • 所以您不希望 LINQ 像通常应该的那样将此查询发送到 SQL?

标签: sql sql-server entity-framework linq


【解决方案1】:

未经测试,但应该可以工作:

 var result = db.Students.Where(x => x.Group.Name == group)
            .GroupBy(g => g.Fullname)
            .Select(i => new
            {
                FullName = i.Key,
                GeneralPoint = i.Sum(s => s.DiamondCount + s.CoinCount)
            })
            .OrderBy(o => o.GeneralPoint)
            .ToList();

【讨论】: