【发布时间】:2017-09-25 16:30:50
【问题描述】:
SQL 查询运行正常:
select o.OpName,isnull(Amount,0) from Setup_tblOperator o
left join
(
select t.opid,sum(isnull(t.Amount,0)) Amount from
Load_tblTransaction t
where cast(t.RequestTime as date)='2017-04-24'
group by t.opid
) t on t.OpId=o.OpId
where o.IsActive=1
我在 LINQ to SQL 中尝试了以下代码:
var trans = (from o in mouDataEntities.Setup_tblOperator
join t in mouDataEntities.Load_tblTransaction
on o.OpId equals t.OpId into ot
from n in ot.Where(
t => DbFunctions.TruncateTime(t.RequestTime) ==
DbFunctions.TruncateTime(seldate))
.DefaultIfEmpty()
select new
{
Operator = o.OpName,
Amount= n.Amount
});
var gt = trans.GroupBy(t => t.Operator)
.Select(n => new { Operator = n.Key, Amount = n.Sum(a=>a.Amount) })
.ToList();
它会抛出一个错误:
转换为值类型“System.Int32”失败,因为物化了 值为空。结果类型的泛型参数或查询 必须使用可空类型。
【问题讨论】:
-
这个错误是不言自明的。您有一个可以为空的 DB 值,并且您正在尝试将其转换为不可为空的
int。 -
谢谢 Yannick Meeus。我期待有人编辑/格式化我的问题。
-
在某些情况下,它不是一个简单的 DB 可空字段,当返回的集合为空时,非可空字段可能会发生这种情况