有没有办法在linq中做到这一点?

时间:2019-10-02 15:30:27

标签: c# asp.net-mvc linq

我通过entitiyframework通过检查数据库中的2张表,得到了已打印但尚未兑现的支票的总和

我尝试了多个查询,但是我对LINQ的经验不是很丰富,并且没有得到理想的结果,以下是我的一些实现。

select sum(checks.Check_Amount) from dbo.ODC_Register checks
left join dbo.vw_BMO_Daily cashed
on checks.Check_Number = cashed.DCheckNo
where cashed.Id is null
and checks.Check_Date < '2019-9-3'

这是我最后尝试的

    var missing = from checks in Context.ODC_Register
                          where(!Context.vw_BMO_Daily.Where(ma => Convert.ToInt32(ma.DCheckNo) == checks.Check_Number && checks.Check_Date <= ma.DatePosted).Any())
                          select new {checks.Check_Amount };

            var missingSum = missing.Sum( x => x.Check_Amount);

我所需要做的就是找到一种方法使之成为LINQ查询

1 个答案:

答案 0 :(得分:1)

虽然可以对SQL进行直接翻译,但也许使用GroupJoin是对LINQ更友好的方法:

var ans = (from checks in Context.ODC_Register
           where checks.Check_Date < new DateTime(2019, 9, 3)
           join cashed in Context.vw_BMP_Daily on checks.Check_Number equals cashed.DCheckNo into cashedj
           where !cashedj.Any()
           select checks.Check_Amount).Sum();

PS不确定ODC_Register的范围变量为什么命名为checks,因为它一次只能进行一次检查-我将其称为check

PPS在SQL和LINQ中,不存在测试通常比使用空的左联接更好:

var an2 = (from checks in Context.ODC_Register
           where checks.Check_Date < new DateTime(2019, 9, 3)
           where !Context.vw_BMP_Daily.Any(cashed => cashed.DCheckNo == checks.Check_Number)
           select checks.Check_Amount).Sum();