如何将此查询字符串转换为linq [英] How do I translate this query string to linq
问题描述
string query =select isnull(sum(amount),0)[amount]来自Recharge.dbo.AirtimePromoTable;
i有一个充满原始查询字符串和连接字符串的项目,现在我是为项目创建实体框架的任务。
如何使用LINQ检查ISNUll和sum SQL
我尝试过的事情:
这就是我所拥有的试过但它没有用......
使用(var Context = new RechargeEntities())
{
var Que =(来自Context.AirtimePromoTables中的b
。选择(b => b.Amount)
.DefaultIfEmpty(0)
.Sum()。ToString());
}
这应该有效:
< span class =code-keyword> using ( var Context = new RechargeEntities() )
{
var Que = Context.AirtimePromoTables
.Sum(b = > ; b.Amount);
}
你没有需要检查金额
是否为空。您甚至不需要将空值转换为零以便能够对它进行求和,因为 Enumerable.Sum方法(IEnumerable(Nullable(Double)))(System.Linq) [ ^ ]接受可空值作为输入参数。
所以,使用:
.Sum(b => b.Amount!= null?b.Amount:0 );
多余!
查看:
< pre lang =c#> double ?[] amount = { null ,空跨度>};
var result = amount.Sum(); // 返回0(零)
或者
double ?[] amount1 = { null , 2 。 5 , 1 。 5 , 0 。 5 , 0 。 25 , 1 。 75 , 3 。 0 ,空跨度>};
var result1 = amount.Sum(); // 返回9.5
祝你好运!
string query = "select isnull(sum(amount),0) [amount] from Recharge.dbo.AirtimePromoTable";
i have a project full of raw query string and connection string and now i was task to create entity framework for the project.
How do i check for ISNUll and sum using LINQ to SQL
What I have tried:
Here is what i have tried but its not working...
using (var Context = new RechargeEntities()) { var Que = (from b in Context.AirtimePromoTables .Select(b => b.Amount) .DefaultIfEmpty(0) .Sum().ToString()); }
This should work:
using (var Context = new RechargeEntities()) { var Que = Context.AirtimePromoTables .Sum(b => b.Amount); }
[EDIT]
You don't need to check wheteveramount
is null or not. You don't even need to convert nulls to zeros to be able to sum it up, because Enumerable.Sum Method (IEnumerable(Nullable(Double))) (System.Linq)[^] accepts nullable values as an input parameter.
So, using:
.Sum(b => b.Amount!=null ? b.Amount : 0);
is redundant!
Check this:
double?[] amounts = {null, null}; var result = amounts.Sum(); //returns 0 (zero)
or
double?[] amounts1 = {null, 2.5, 1.5, 0.5, 0.25, 1.75, 3.0, null}; var result1 = amounts.Sum(); //returns 9.5
Good luck!
这篇关于如何将此查询字符串转换为linq的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!