在实体框架中,如何在Select子句中使用聚合函数?

时间:2019-05-23 14:33:03

标签: asp.net entity-framework linq

是否可以将下面的工作SQL语句转换为Entity Framework查询?

SELECT Year([Model Date])
       ,Model
       ,COUNT(SERIAL) AS [Model Count]
       ,(SUM([SCORE])/COUNT(SERIAL)) as [Average SCORE]
       ,(COUNT(SERIAL)/SUM([SCORE])) * 100 AS [Score Rate]
FROM [MODELS]
WHERE Model IS NOT NULL 
AND [ACE PROFILE] <> 0
AND SERIAL IS NOT NULL
GROUP BY Model, Year([Model Date])

1 个答案:

答案 0 :(得分:2)

public class Db : DbContext
{
    public Db(string connection) : base(connection) {}
    public DbSet<MODEL> MODELS { get; set; }
}

[Table("MODELS")]
public class MODEL
{
    [Key]
    public string Model { get; set; }
    [System.ComponentModel.DataAnnotations.Schema.Column("ACE PROFILE")]
    public int? ACE_PROFILE { get; set; }
    public int? SERIAL { get; set; }
    public int? SCORE { get; set; }
    [System.ComponentModel.DataAnnotations.Schema.Column("Average SCORE")]
    public int Average_SCORE { get; set; }
    [System.ComponentModel.DataAnnotations.Schema.Column("Model Date")]
    public DateTime Model_Date { get; set; }
}

void Main()
{
    var db = new Db(Connection.ConnectionString);

    var result =    from T in db.MODELS
                    where T.Model != null && T.ACE_PROFILE != 0 && T.SERIAL != null
                    group T by new { DateYear = T.Model_Date.Year, T.Model } into g
                    select new
                    {
                        g.Key.DateYear,
                        g.Key.Model,
                        Model_Count = g.Count(c => c.SERIAL != null),
                        Average_SCORE = g.Sum(c => c.SCORE ) / g.Count(c => c.SERIAL != null),
                        Score_Rate = (g.Count(c => c.SERIAL != null) / g.Sum(c => c.SCORE)) * 100
                    };
}