gpt4 book ai didi

c# - 使用平均值时 linq 查询出错

转载 作者:太空宇宙 更新时间:2023-11-03 18:33:26 25 4
gpt4 key购买 nike

我的数据库中有两个表,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 行。我想按图片 ID 对 pictureratings 表进行分组,然后计算点赞数。我想在 totalrating 属性的 picture 表中显示那些喜欢的内容。

根据我现在的情况,我可以编写以下代码

 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
};

我正在使用网络 API 返回查询总数。我正在显示 picture 属性,例如 iduserpicTitlepicFilenamepictimenuditylevelfakeslevel

现在一切都运行顺利,但是当我添加 totalrating = pl.Average(c => c.likenumber) 时,我得到一个异常提示

The cast to value type 'Double' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.

如何消除错误?

最佳答案

可能是pl没有记录的问题,试试

替换

totalrating = pl.Average(c => c.likenumber) // This line is causing error

totalrating = pl.DefaulIfEmpty(0).Average(c => c.likenumber) 

关于c# - 使用平均值时 linq 查询出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19009901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com