gpt4 book ai didi

c# - 这个 SQL 语句的等效 LINQ to SQL 查询表达式是什么?

转载 作者:行者123 更新时间:2023-11-30 21:41:10 25 4
gpt4 key购买 nike

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/

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