实体框架获取集合计数而不是整个集合

时间:2021-03-26 15:38:00

标签: entity-framework entity-framework-core

我在 Blazor WASM 应用程序中使用 Entity Framework Core。我有一个包含列表的电影类。我想显示带有评分计数和评分平均值的电影列表,但我不需要完整的评分列表来返回列表。

public class Movie
{
   public int Id {get;set;}
   public string Name  {get;set;}

   public List<Rating> Ratings {get;set;}
}

public class Rating
{
  public int Id {get;set;}
  public decimal Value {get;set;}

 public int MovieId {get;set;}
 public Movie Movie {get;set;}
}

public async Task<IEnumerable<Movie>> GetAllAsync()
        {
            try
            {
                return await _dataContext.Movies.Include(a => a.Rating).ToListAsync();
            }
            catch(Exception ex)
            {
                _logger.LogError(ex, "Error in GetAllAsync()");
                throw;
            }
        }

我最终希望列表看起来像

速度与激情 26 评分 4.5 平均

获得 145 个评分,平均 3.7 个

1 个答案:

答案 0 :(得分:1)

像这样投影出聚合:

var q = from m in db.Movies
        select new 
          { 
            m.Name, 
            Ratings = m.Ratings.Count(), 
            AverageRating = m.Ratings.Average(r => r.Value) 
          };

return await q.ToListAsync();
相关问题