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

标签 c# sql asp.net linq t-sql

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/

相关文章:

mysql - 行总和

javascript - 如何在客户端设置自定义验证器 isValid 属性?

c# - 使属性彼此不兼容?

c# - 我可以在 C# 中通过引用传递原始类型吗?

c# - 遍历枚举器时的集合

c# - 将控件添加到 Gridview 单元格

c# - jQuery Ajax、MVC 和查询字符串

c# - 如何将适用于整数的通用表达式树代码应用于枚举(例如,如何使 Expression.PostIncrementAssign() 适用于枚举?)?

mysql - 使用带有 MySQL 链接服务器的 openquery 时,宽 varchar 字段导致 "Requested conversion is not supported"错误

SQL 查询而不是游标