在过去30天内播放最多的歌曲

时间:2017-12-10 20:04:08

标签: c# asp.net entity-framework

我正在尝试在我的主页上显示按过去30天内播放次数最多的歌曲。播放歌曲时,会调用ajax函数:

注意:我已经在这个页面的下方进一步加粗了我认为问题仍然存在的部分,但是为了以防万一,我想提供导致问题的信息

function insertSongPlay(songID)

{
    $.ajax
    ({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        url: "/Album/InsertSongPlay/",
        data: JSON.stringify({ "songID": songID }),
        success: function(data)
        {

            console.log("submitted");
            console.log(songID);
            //TODO: Indicate Success
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            //TODO: Indicate Error
            console.log(errorThrown);
        }
    });
}

这对应于我的控制器中的这个JsonSubmit:

[HttpPost]
public JsonResult InsertSongPlay(int songID)
{
    try
    {
        EntityDataAccess.InsertSongPlay(songID);
        return Json(true);
    }
    catch(Exception ex)
    {
        throw ex;
    }
}

在我的entitydataaccess.cs中使用了这种方法:

public static SongPlayDaily InsertSongPlay(int songID)
{
    using(var Context = GetContext())
    {
        var today = DateTime.Now.Date;
        var currentSongPlay = Context.SongPlayDailies.FirstOrDefault(x => x.SongID == songID && x.PlayDate == today);
        if (currentSongPlay != null)
            currentSongPlay.NumberOfPlays++;
        else
        {
            currentSongPlay = new SongPlayDaily();
            currentSongPlay.SongID = songID;
            currentSongPlay.PlayDate = DateTime.Now.Date;
            currentSongPlay.NumberOfPlays = 1;
            Context.SongPlayDailies.Add(currentSongPlay);
        }
        Context.SaveChanges();
        return currentSongPlay;
    }
}

现在在我的主页上,我相信这就是我的问题所在,但我的方法是尝试在我的主页上对相册进行排序:

public static List<Song> GetTopPlayedSongsByCount(int count)
{
    using(var Context = GetContext())
    {
        var lastDate = DateTime.Now.Date.AddDays(-30);
        var songIDs = Context.SongPlayDailies.Where(x => DateTime.Compare(x.PlayDate, lastDate) >= 0).GroupBy(x => x.SongID).Select(x => new { SongID = x.Key, NumberOfPlays = x.Sum(y => y.NumberOfPlays) }).OrderByDescending(x => x.NumberOfPlays).Take(count).Select(x => x.SongID).ToList();
        return Context.Songs.Include("Album").Include("Album.AccountInfo").Where(x => songIDs.Any(y => y == x.SongID)).ToList();
    }
}

但是,相册在我上传它们的日期(从最旧到最新)保持订购

编辑:添加了Song.cs

namespace Domain.Data
{
    using System;
    using System.Collections.Generic;

    public partial class Song
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Song()
        {
            this.DownloadHistories = new HashSet<DownloadHistory>();
            this.SongPlayDailies = new HashSet<SongPlayDaily>();
        }

        public int SongID { get; set; }
        public int AlbumID { get; set; }
        public string Title { get; set; }
        public string Artist { get; set; }
        public Nullable<System.DateTime> Duration { get; set; }
        public Nullable<int> BPM { get; set; }
        public string URL { get; set; }
        public Nullable<bool> ApprovalFL { get; set; }
        public System.DateTime UploadDate { get; set; }

        public virtual Album Album { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<DownloadHistory> DownloadHistories { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<SongPlayDaily> SongPlayDailies { get; set; }
    }
}

1 个答案:

答案 0 :(得分:1)

您可以将第二个查询集成到第一个查询中:

public static List<Song> GetTopPlayedSongsByCount(int count)
{
    using(var Context = GetContext())
    {
        var lastDate = DateTime.Now.Date.AddDays(-30);
        var result = Context.SongPlayDailies.Where(x => DateTime.Compare(x.PlayDate, lastDate) >= 0)
          .GroupBy(x => x.SongID)
          .Select(x => new { SongID = x.Key, NumberOfPlays = x.Sum(y => y.NumberOfPlays) })
          .OrderByDescending(x => x.NumberOfPlays)
          .Take(count)
          .Select(x => Context.Songs.Include("Album").Include("Album.AccountInfo").FirstOrDefault(y=>y.SongId==x.SongId))
          .Where(z=> z!=null).ToList();
        return result;
    }
}