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();
它抛出一个错误:
The cast to value type 'System.Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.
最佳答案
在某些情况下,简单的 SQL 到 C# 的转换会被接受,但在运行时会失败。在 C# 中,set.DefaultIfEmpty().Select(n => n.Amount)
,其中n.Amount
类型为int
,结果类型为 IEnumerable<int>
。它会失败并显示 NullReferenceException
如果set
是空的,因为在这种情况下 n
将变成null
以及。因此,您没有理由需要 int?
,因为你永远无法得到 null
结果。
在 SQL 中,这并不那么容易。检索 LEFT JOIN
引入的默认行的列有效,并生成 NULL
.
但是 C# 代码需要 int
类型的值,以及 int
不可能null
.
您需要找到某种方法来欺骗类型系统,以便您可以指定如何 null
应该处理。一个简单的转换就足够了:
改变
Amount = n.Amount
至
Amount = (int?) n.Amount
或者,转null
进入0
,
Amount = (int?) n.Amount ?? 0
关于c# - 此 SQL 语句的等效 LINQ to SQL 查询表达式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43665224/