0

我有两个表,picturepictureratings我的数据库中。

public partial class picture
{
    public int idpicture { get; set; }
    public int iduser { get; set; }
    public string picTitle { get; set; }
    public string picFilename { get; set; }
    public System.DateTime pictime { get; set; }
    public int nuditylevel { get; set; }
    public int fakeslevel { get; set; }

    // This property will hold the total accumulated/summed 
    // up rating of a picture
    public int totalrating { get; set; }    
}

public partial class pictureratings 
{
    public int idrating { get; set; }
    public int idpictures { get; set; }
    public int iduser { get; set; }
    public System.DateTime iddatetime { get; set; }
    public int iduserrateddby { get; set; }
    public int rating { get; set; } 
}

对于每个评级,pictureratings将创建一个新行。我想pictureratings按图片ID对表格进行分组,然后计算喜欢。我想在picture表格中显示那些喜欢totalrating在属性

所以根据我到目前为止的研究,我能够编写这段代码

var total = from p in db.picturedetails
            join l in db.picturelikes on p.idpictures equals l.idpictures 
            group l by l.idpictures into g
            select new 
            {
                IdUserPic = g.First().iduser,
                IdPictures = g.First().idpictures,
                totalrating = g.Count()    
            }

我正在使用 web api 返回查询总数。所以我的问题来了:如何显示, , ,和等picture属性?我做对了吗?我该怎么做?iduserpicTitlepicFilenamepictimenuditylevelfakeslevel

4

2 回答 2

1

我认为组加入是您正在寻找的:

var total = from p in db.picturedetails
            join l in db.picturelikes on p.idpicture equals l.idpictures into pl
            select new
            {
                Picture = p,
                AverageRating = pl.Any()
                                    ? pl.Average(l => l.rating)
                                    : (double?)null,
                RatingsCount = pl.Count(),
                TotalRating = pl.Sum(l => (float?)l.likenumber) ?? 0
            };

如果一张图片没有喜欢,这将给出该图片的0总数和null平均值。

于 2013-09-25T14:21:39.153 回答
1

您可以对匿名类进行分组。这样您就可以同时访问 p & l 属性。
看起来像这样:

var total = from p in db.picturedetails
            join l in db.picturelikes on p.idpictures equals l.idpictures 
            group new {p,l} by l.idpictures into g
            select new 
            {
                IdUserPic = g.First().p.iduser,
                IdPictures = g.First().p.nuditylevel,
                totalrating = g.Count()    
            }
于 2013-09-25T14:24:15.050 回答