.无行的 Sum() 返回类型

.Sum() return type for no rows

提问人:AkshatSparrow 提问时间:10/4/2023 最后编辑:AkshatSparrow 更新时间:10/4/2023 访问量:64

问:

我有两个表“问题”和“答案”。它们的关联如下:

    public class Answer
    {
        public Guid Id { get; set; }

        public Guid? QuestionId { get; set; }
        public virtual Question? Question { get; set; }
    }

    public class Question
    {
        public Guid Id { get; set; }

        [MaxLength(1024)] public string Question { get; set; }

        public int? MaxMarks { get; set; }
    }

评分系统仅适用于某些问题,这就是为什么可以为 null 的原因MaxMarks

        TotalScore = s.Answers
                        .Where(a => a.Question.MaxMarks.HasValue)
                        .Sum(a => a.Question.MaxMarks)

我在这一行上遇到错误

System.InvalidCastException:无法将“System.Int64”类型的对象强制转换为“System.Int32”类型。 在 Microsoft.Data.SqlClient.SqlBuffer.get_Int32()

我试图显式地将其转换为 int ,但它不起作用。 有谁知道这里到底发生了什么?

此外,当没有向它传递任何行时,函数究竟会返回什么:( 或.Sum()null0)

C# asp.net 实体框架 LINQ EF 代码优先

评论

0赞 Fildor 10/4/2023
“还有,究竟会是什么.Sum() 函数在没有传递任何行时返回“——你可以很容易地找到它。您出现问题的原因是:您是否检查了结果是否为 > int。MaxValue?
0赞 AkshatSparrow 10/4/2023
好吧,我的结果不会超过最大 int 值,而且列中的所有值暂时都是空的MaxMarks
0赞 Fildor 10/4/2023
您之前是否将类型更改为 并且是否使用该版本在数据库中创建表?它是什么列类型?longintlong
2赞 User12345 10/4/2023
请检查您的数据库。是 int 还是 bigint 在表上?MaxMarks Question
0赞 AkshatSparrow 10/4/2023
非常感谢你@HeinzSiahaan,@Fildor,是的,我之前使用过,忘记更新数据库。bigint

答: 暂无答案