Question

I am new to LINQ, I am just starting to understand its syntax but still decided to use Linqer application to convert my SQL statements to LINQ statements. However, LINQ queries do not produce the same result.

Here's my SQL query:

SELECT ISNULL(SUM(linehaul + accessorial), 0) FROM costs
WHERE
ordnumber = 19374911

It converts to this LINQ:

From Costs In
(From Costs In db.Costs
Where
  CLng(Costs.ordnumber) = 19374911
Select 
  Column1 = CType((Costs.linehaul + Costs.accessorial),Decimal?),
  ordnumber = Costs.ordnumber,
  linehaul = Costs.linehaul,
  accessorial = Costs.accessorial,
  Dummy = "x"
)
Group Costs By Costs.Dummy Into g = Group 
Select New With {
  .Column1 = If(CType(g.Sum(Function(p) p.linehaul + p.accessorial),Decimal?) Is Nothing,0,g.Sum(Function(p) p.linehaul + p.accessorial))
}

I can't really say that I understand this conversion 100% but it's not the point. If I DO have costs for the given ordnumber then the results are consistent but if the costs aren't found for the given ordnumber LINQ returns an empty result set instead of returning the default value of "0" like my SQL does.

What do I need to add to my LINQ to make it return zero instead of an empty result?

Was it helpful?

Solution

You should be able to do something like this (should work for both EF and L2SQL):

int cost = Context.Costs.Where(x => x.ordnumber == 19374911)
    .Sum(y => y.linehaul + y.accessorial)) ?? 0;

VB.net should be something like this: (not tested)

Dim cost As Integer = If(Context.Costs.Where(Function(cost) cost.ordnumber = 19374911).Sum(Function(x) x.linehaul + y.accessorial)), 0)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top