问题描述
我的数据库中有两个表picture
和pictureratings
.
I have two tables, picture
and pictureratings
in my database.
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
行.我想按图片ID将pictureratings
表分组,然后计算喜欢人数.我想在totalrating
属性的picture
表中显示喜欢的人.
For every rating a new pictureratings
row will be created. I want to group pictureratings
table by the picture id and then count the likes. I want to show those likes in picture
table in totalrating
property.
所以按照我现在的样子,我可以编写以下代码
So as per my now I am able to write the following code
var combo = from p in db.picturedetails
join l in db.picturelikes on p.idpictures equals l.idpictures into pl
select new LikesandPictureDetails
{
IdUserPic = p.iduser,
IdPicturess =p.idpictures,
Likes = p.likes,
NudityLevel = p.nuditylevel,
PicTitle = p.picTitle,
PicTime = p.pictime,
picFilename=p.picFilename,
Count=pl.Count(),
totalrating = pl.Average(c => c.likenumber) // This line is causing error
};
我正在使用Web API返回查询总数.我正在显示picture
属性,例如iduser
,picTitle
,picFilename
,pictime
,nuditylevel
和fakeslevel
.
I am using web api to return query total. I am showing picture
properties like iduser
, picTitle
, picFilename
, pictime
, nuditylevel
and fakeslevel
.
目前,一切正常,但是当我添加totalrating = pl.Average(c => c.likenumber)时,我得到一个异常提示
As per now every thing runs smooth, but when I add totalrating = pl.Average(c => c.likenumber) , I get an exception saying
如何清除错误?
推荐答案
也许问题在于pl没有记录,请尝试
Maybe the problem is that pl has no records, try
替换
totalrating = pl.Average(c => c.likenumber) // This line is causing error
使用
totalrating = pl.DefaulIfEmpty(0).Average(c => c.likenumber)
这篇关于使用平均值时LINQ查询中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!