Ron*_*rby 7 .net c# linq orm entity-framework
鉴于此查询:
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
}
Run Code Online (Sandbox Code Playgroud)
如果服务没有任何保留,则抛出此异常:
System.InvalidOperationException:转换为值类型"Int32"失败,因为实现值为null.结果类型的泛型参数或查询必须使用可空类型.
我明白了,但我应该怎么处理呢?我的意图是如果没有预订,则将HeadCount分配为0.
Cra*_*ntz 11
有一个更简单的解决方案:
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
}
Run Code Online (Sandbox Code Playgroud)
注意演员.这也可能比@ Ahmad的建议产生更简单的SQL.
从本质上讲,你只是在帮助推断类型推理.
你应该检查一下:
HeadCount = s.Reservations != null ? s.Reservations.Sum(r => r.PartySize) : 0,
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9769 次 |
| 最近记录: |