gpt4 book ai didi

c# - 在子对象属性上使用 Sum 的 LINQ to Entities 查询问题

转载 作者:太空狗 更新时间:2023-10-29 19:53:20 25 4
gpt4 key购买 nike

给出这个查询:

from s in services
select new
{
s.Id,
s.DateTime,
Class = s.Class.Name,
s.Location,
s.Price,
HeadCount = s.Reservations.Sum(r => r.PartySize), // problem here. r.PartySize is int
s.MaxSeats
}

如果服务没有任何保留,则抛出此异常:

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

我明白了,但我该如何处理呢?我的意图是,如果没有预订,则将 HeadCount 分配为 0。

最佳答案

还有一个更简单的解决方案:

from s in services
select new
{
s.Id,
s.DateTime,
Class = s.Class.Name,
s.Location,
s.Price,
HeadCount = (int?)s.Reservations.Sum(r => r.PartySize),
s.MaxSeats
}

注意类型转换。这也可能产生比@Ahmad 的建议更简单的 SQL。

从本质上讲,您只是在帮助进行类型推断。

关于c# - 在子对象属性上使用 Sum 的 LINQ to Entities 查询问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3814541/

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